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

78 lines
1.7 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"
)
// @summary Register an account
// @tags account
// @accept json
// @produce json
// @param register body v1.Register true "alice" "supersecretpassword"
// @success 200 {object} v1.Token
// @response default {object} v1.Error "There was an error"
// @router /v1/account/register [post]
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)
}