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

95 lines
2.4 KiB
Go
Raw Normal View History

2024-06-03 13:55:57 +00:00
// Copyright 2024 perp (supernets)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
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 Account registration
// @description Register an account
// @tags account
// @accept json
// @produce json
// @param register body v1.Register true "alice" "supersecretpassword"
// @success 200 {object} models.Token
// @failure 400 {object} models.Error "MissingBody | UsernameTaken"
// @failure 403 {object} models.Error "RegistrationDisabled"
2024-06-04 15:00:53 +00:00
// @failure 500 {object} models.Error "DatabaseError | InternalServerError"
// @router /v1/account/register [post]
func Register(ctx *context.Context) {
// Check if registration is disabled
if ctx.Config.Auth.Disabled {
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
account, err := ctx.Db.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
err = ctx.Db.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
account, err = ctx.Db.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)
}