package auth
import (
"context"
"fmt"
"net/http"
"git.slaventius.ru/test3k/auth/internal/config"
db "git.slaventius.ru/test3k/auth/internal/transport/grpc"
"git.slaventius.ru/test3k/umate/pkg/logger"
mux "github.com/go-chi/chi/v5"
"google.golang.org/grpc/status"
)
// ...
type AuthServer struct {
db * db . AuthDBClient
Router * mux . Mux
config * config . Config
logger * logger . Logger
ctx context . Context
}
func NewServer ( ctx context . Context , config * config . Config ) * AuthServer {
s := & AuthServer {
db : db . NewDBClient ( ctx , config ) ,
Router : mux . NewMux ( ) ,
config : config ,
logger : logger . NewLogger ( "test3k:authService" , config . Sentry . DSN ) ,
ctx : ctx ,
}
//
s . Router . Get ( "/api/v1/healthz" , healthz ( s ) )
//
s . Router . Post ( "/api/v1/login" , login ( s ) )
s . Router . Post ( "/api/v1/registration" , registration ( s ) )
s . Router . Post ( "/api/v1/confirmation" , confirmation ( s ) )
return s
}
func ( s * AuthServer ) GracefulStop ( ) error {
return s . db . Close ( )
}
func healthz ( s * AuthServer ) http . HandlerFunc {
return func ( w http . ResponseWriter , r * http . Request ) {
w . WriteHeader ( http . StatusOK )
w . Write ( [ ] byte ( "ok" ) )
}
}
func login ( s * AuthServer ) http . HandlerFunc {
return func ( w http . ResponseWriter , r * http . Request ) {
uid := r . FormValue ( "uid" )
password := r . FormValue ( "password" )
err := s . db . Login ( uid , password )
if err != nil {
status := status . Convert ( err )
//
s . logger . Error ( status . Message ( ) )
//
w . Write ( [ ] byte ( status . Message ( ) ) )
return
}
w . Write ( [ ] byte ( fmt . Sprintf ( "Success login for %s" , uid ) ) )
}
}
func registration ( s * AuthServer ) http . HandlerFunc {
return func ( w http . ResponseWriter , r * http . Request ) {
uid := r . FormValue ( "uid" )
email := r . FormValue ( "email" )
password := r . FormValue ( "password" )
_ , err := s . db . Registration ( uid , email , password )
if err != nil {
status := status . Convert ( err )
//
s . logger . Error ( status . Message ( ) )
//
w . Write ( [ ] byte ( status . Message ( ) ) )
return
}
w . Write ( [ ] byte ( fmt . Sprintf ( "Success registration for %s" , uid ) ) )
}
}
func confirmation ( s * AuthServer ) http . HandlerFunc {
return func ( w http . ResponseWriter , r * http . Request ) {
code := r . FormValue ( "code" )
err := s . db . Confirmation ( code )
if err != nil {
status := status . Convert ( err )
//
s . logger . Error ( status . Message ( ) )
//
w . Write ( [ ] byte ( status . Message ( ) ) )
return
}
w . Write ( [ ] byte ( fmt . Sprintf ( "Success confirmation for %s" , code ) ) )
}
}