add admin add cmd
This commit is contained in:
parent
50690f9f94
commit
74f43731b5
1 changed files with 63 additions and 0 deletions
63
adminadd.go
Normal file
63
adminadd.go
Normal file
|
@ -0,0 +1,63 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/pquerna/otp/totp"
|
||||||
|
"golang.org/x/crypto/scrypt"
|
||||||
|
"nim.jasinco.work/app/nimdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
pgurl := os.Getenv("POSTGRES_URL")
|
||||||
|
conn, err := pgx.Connect(context.Background(), pgurl)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
salt := os.Getenv("SALT")
|
||||||
|
|
||||||
|
db := nimdb.New(conn)
|
||||||
|
tx, err := conn.Begin(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln(err.Error())
|
||||||
|
}
|
||||||
|
qtx := db.WithTx(tx)
|
||||||
|
defer tx.Rollback(context.Background())
|
||||||
|
|
||||||
|
fmt.Print("UserName and password (split by space): ")
|
||||||
|
var name, password string
|
||||||
|
_, err = fmt.Scanf("%s %s", &name, &password)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
key, err := totp.Generate(totp.GenerateOpts{Issuer: "TCIVS_NIMING", AccountName: name})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln(err)
|
||||||
|
}
|
||||||
|
secret := key.Secret()
|
||||||
|
log.Println(secret, key.Issuer(), key.AccountName())
|
||||||
|
fmt.Print("Verify TOTP Code: ")
|
||||||
|
var code string
|
||||||
|
_, err = fmt.Scanf("%s", &code)
|
||||||
|
if !totp.Validate(code, secret) {
|
||||||
|
gen, err := totp.GenerateCode(secret, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln("Validation not succed, can't gen code, err:", err.Error())
|
||||||
|
}
|
||||||
|
log.Fatalln("Velidation not succed, CODE should be: ", gen)
|
||||||
|
}
|
||||||
|
hashed, err := scrypt.Key([]byte(password), []byte(salt), 32768, 8, 1, 32)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln(err.Error())
|
||||||
|
}
|
||||||
|
qtx.AdminCreateAccount(context.Background(), nimdb.AdminCreateAccountParams{Username: name, Password: base64.StdEncoding.EncodeToString(hashed), Totp: secret})
|
||||||
|
tx.Commit(context.Background())
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue