gopay/internal/router/api/v1/account/register.go

70 lines
1.4 KiB
Go
Raw Normal View History

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"
)
func Register(ctx *context.Context) {
// Check if registration is disabled
2024-06-06 18:18:46 +00:00
if ctx.Config.Auth.Register {
2024-06-04 15:00:53 +00:00
ctx.Error(403, "RegistrationDisabled")
return
}
// Store body
var body *v1.Register
// Bind JSON
err := ctx.BindJSON(&body)
if err != nil {
2024-06-04 15:00:53 +00:00
ctx.Error(400, "MissingBody")
return
}
// Select account by username
2024-06-06 18:18:46 +00:00
account, err := ctx.Database.Account.SelectByUsername(body.Username)
if err != nil {
2024-06-04 15:00:53 +00:00
ctx.Error(500, "DatabaseError")
return
}
2024-06-03 15:55:25 +00:00
// Compare username
if account.Username == body.Username {
2024-06-04 15:00:53 +00:00
ctx.Error(400, "UsernameTaken")
return
}
// Hash password
password, err := bcrypt.GenerateFromPassword([]byte(body.Password), ctx.Config.Auth.Cost)
if err != nil {
2024-06-04 15:00:53 +00:00
ctx.Error(500, "InternalServerError")
return
}
// Insert account
2024-06-06 18:18:46 +00:00
err = ctx.Database.Account.Insert(body.Username, string(password))
if err != nil {
2024-06-04 15:00:53 +00:00
ctx.Error(500, "DatabaseError")
return
}
// Select account by username
2024-06-06 18:18:46 +00:00
account, err = ctx.Database.Account.SelectByUsername(body.Username)
if err != nil {
2024-06-04 15:00:53 +00:00
ctx.Error(500, "DatabaseError")
return
}
// Generate token
token, err := jwt.Encode(account.ID)
if err != nil {
2024-06-04 15:00:53 +00:00
ctx.Error(500, "InternalServerError")
return
}
2024-06-04 15:00:53 +00:00
ctx.Token(token)
}