71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
package account
|
|
|
|
import (
|
|
"git.supernets.org/perp/gopay/internal/context"
|
|
"git.supernets.org/perp/gopay/internal/jwt"
|
|
v1 "git.supernets.org/perp/gopay/internal/models/v1"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// Register an account
|
|
func Register(ctx *context.Context) {
|
|
// Check if registration is disabled
|
|
if ctx.Config.Auth.Register {
|
|
ctx.Error(403, "RegistrationDisabled")
|
|
return
|
|
}
|
|
|
|
// Store body
|
|
var body *v1.Register
|
|
|
|
// Bind JSON
|
|
err := ctx.BindJSON(&body)
|
|
if err != nil {
|
|
ctx.Error(400, "MissingBody")
|
|
return
|
|
}
|
|
|
|
// Select account by username
|
|
account, err := ctx.Database.Account.SelectByUsername(body.Username)
|
|
if err != nil {
|
|
ctx.Error(500, "DatabaseError")
|
|
return
|
|
}
|
|
|
|
// Compare username
|
|
if account.Username == body.Username {
|
|
ctx.Error(400, "UsernameTaken")
|
|
return
|
|
}
|
|
|
|
// Hash password
|
|
password, err := bcrypt.GenerateFromPassword([]byte(body.Password), ctx.Config.Auth.Cost)
|
|
if err != nil {
|
|
ctx.Error(500, "InternalServerError")
|
|
return
|
|
}
|
|
|
|
// Insert account
|
|
err = ctx.Database.Account.Insert(body.Username, string(password))
|
|
if err != nil {
|
|
ctx.Error(500, "DatabaseError")
|
|
return
|
|
}
|
|
|
|
// Select account by username
|
|
account, err = ctx.Database.Account.SelectByUsername(body.Username)
|
|
if err != nil {
|
|
ctx.Error(500, "DatabaseError")
|
|
return
|
|
}
|
|
|
|
// Generate token
|
|
token, err := jwt.Encode(account.ID)
|
|
if err != nil {
|
|
ctx.Error(500, "InternalServerError")
|
|
return
|
|
}
|
|
|
|
ctx.Token(token)
|
|
}
|