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

73 lines
1.8 KiB
Go

// 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 login
// @description Login to 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/login [post]
func Login(ctx *context.Context) {
// 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.Db.Account.SelectByUsername(body.Username)
if err != nil {
ctx.Error(500, "DatabaseError")
return
}
// Compare username
if account.Username != body.Username {
ctx.Error(400, "InvalidUsername")
return
}
// Compare password
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(body.Password))
if err != nil {
ctx.Error(400, "InvalidPassword")
return
}
// Generate token
token, err := jwt.Encode(account.ID)
if err != nil {
ctx.Error(500, "InternalServerError")
return
}
ctx.Token(token)
}