B: fix issues preventing logins from happening and add logging

This commit is contained in:
Preston Baxter 2023-10-28 17:29:57 -05:00
parent f7dc37fb02
commit 1bfcdce01a
5 changed files with 31 additions and 15 deletions

View File

@ -26,11 +26,13 @@ func SignUpHandler (c *gin.Context) {
reqBody.Password = c.Request.FormValue("password") reqBody.Password = c.Request.FormValue("password")
if reqBody.Email == "" { if reqBody.Email == "" {
log.Warn("Request contained no email")
renderTempl(c, templates.SignupPage("Please provide an email")) renderTempl(c, templates.SignupPage("Please provide an email"))
return return
} }
if reqBody.Password == "" { if reqBody.Password == "" {
log.Warn("Request contained no password")
renderTempl(c, templates.SignupPage("Please provide a password")) renderTempl(c, templates.SignupPage("Please provide a password"))
return return
} }
@ -38,11 +40,13 @@ func SignUpHandler (c *gin.Context) {
//Verify username and password //Verify username and password
user, err := mongo.FindUserByEmail(reqBody.Email) user, err := mongo.FindUserByEmail(reqBody.Email)
if err != nil { if err != nil {
log.WithError(err).Errorf("Failed to lookup user: %s", reqBody.Email)
renderTempl(c, templates.SignupPage("Error occured. Please try again later")) renderTempl(c, templates.SignupPage("Error occured. Please try again later"))
return return
} }
if user != nil { if user != nil {
log.Warnf("User: %s, already exists", reqBody.Email)
renderTempl(c, templates.SignupPage(fmt.Sprintf("user already exists for %s", reqBody.Email))) renderTempl(c, templates.SignupPage(fmt.Sprintf("user already exists for %s", reqBody.Email)))
return return
} }
@ -51,6 +55,7 @@ func SignUpHandler (c *gin.Context) {
passHash, err := bcrypt.GenerateFromPassword([]byte(reqBody.Password), 10) passHash, err := bcrypt.GenerateFromPassword([]byte(reqBody.Password), 10)
if err != nil { if err != nil {
log.WithError(err).Errorf("Passowrd hash failed for user: %s", reqBody.Email)
renderTempl(c, templates.SignupPage("Signup failed. Please try again later")) renderTempl(c, templates.SignupPage("Signup failed. Please try again later"))
return return
} }
@ -60,6 +65,7 @@ func SignUpHandler (c *gin.Context) {
err = mongo.SaveModel(user) err = mongo.SaveModel(user)
if err != nil { if err != nil {
log.WithError(err).Errorf("Failed to write user to DB for user: %s", reqBody.Email)
renderTempl(c, templates.SignupPage("Signup failed. Please try again later")) renderTempl(c, templates.SignupPage("Signup failed. Please try again later"))
return return
} }
@ -72,8 +78,9 @@ func SignUpHandler (c *gin.Context) {
}, },
) )
jwtStr, err := token.SignedString(conf.JwtSecret) jwtStr, err := token.SignedString([]byte(conf.JwtSecret))
if err != nil { if err != nil {
log.WithError(err).Errorf("Failed to encode jwt for user: %s", reqBody.Email)
renderTempl(c, templates.SignupPage("Signup failed. Please try again later")) renderTempl(c, templates.SignupPage("Signup failed. Please try again later"))
return return
} }
@ -94,11 +101,13 @@ func LoginHandler(c *gin.Context) {
reqBody.Password = c.Request.FormValue("password") reqBody.Password = c.Request.FormValue("password")
if reqBody.Email == "" { if reqBody.Email == "" {
log.Warn("Request contained no email")
renderTempl(c, templates.LoginPage("Please provide an email")) renderTempl(c, templates.LoginPage("Please provide an email"))
return return
} }
if reqBody.Password == "" { if reqBody.Password == "" {
log.Warn("Request contained no password")
renderTempl(c, templates.LoginPage("Please provide a password")) renderTempl(c, templates.LoginPage("Please provide a password"))
return return
} }
@ -106,17 +115,20 @@ func LoginHandler(c *gin.Context) {
//Verify username and password //Verify username and password
user, err := mongo.FindUserByEmail(reqBody.Email) user, err := mongo.FindUserByEmail(reqBody.Email)
if err != nil { if err != nil {
log.WithError(err).Errorf("Failed to lookup user: %s", reqBody.Email)
renderTempl(c, templates.LoginPage(err.Error())) renderTempl(c, templates.LoginPage(err.Error()))
return return
} }
if user == nil { if user == nil {
log.Warnf("No user was found for: %s", reqBody.Email)
renderTempl(c, templates.LoginPage(fmt.Sprintf("No user found for %s", reqBody.Email))) renderTempl(c, templates.LoginPage(fmt.Sprintf("No user found for %s", reqBody.Email)))
return return
} }
if err := bcrypt.CompareHashAndPassword([]byte(user.PassowrdHash), []byte(reqBody.Password)); err != nil { if err := bcrypt.CompareHashAndPassword([]byte(user.PassowrdHash), []byte(reqBody.Password)); err != nil {
renderTempl(c, templates.LoginPage("Email and password are incorrect")) log.Warnf("Password does not match for user: %s", reqBody.Email)
renderTempl(c, templates.LoginPage("Email or password are incorrect"))
return return
} }
@ -128,7 +140,7 @@ func LoginHandler(c *gin.Context) {
}, },
) )
jwtStr, err := token.SignedString(conf.JwtSecret) jwtStr, err := token.SignedString([]byte(conf.JwtSecret))
if err != nil { if err != nil {
renderTempl(c, templates.LoginPage("An error occured. Please try again later")) renderTempl(c, templates.LoginPage("An error occured. Please try again later"))
} }

View File

@ -5,6 +5,7 @@ import (
"git.preston-baxter.com/Preston_PLB/capstone/frontend-service/db" "git.preston-baxter.com/Preston_PLB/capstone/frontend-service/db"
"git.preston-baxter.com/Preston_PLB/capstone/frontend-service/middleware" "git.preston-baxter.com/Preston_PLB/capstone/frontend-service/middleware"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
) )
var mongo *db.DB var mongo *db.DB
@ -19,6 +20,11 @@ func BuildRouter(r *gin.Engine) {
panic(err) panic(err)
} }
log = logrus.New()
log.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
})
r.GET("/", middleware.AuthMiddleware(false) ,LandingPage) r.GET("/", middleware.AuthMiddleware(false) ,LandingPage)
r.GET("/login", middleware.AuthMiddleware(false), LoginPage) r.GET("/login", middleware.AuthMiddleware(false), LoginPage)
r.GET("/signup", middleware.AuthMiddleware(false), SignUpPage) r.GET("/signup", middleware.AuthMiddleware(false), SignUpPage)

View File

@ -2,8 +2,8 @@ package models
import "time" import "time"
type model struct { type CommonFields struct {
EntityType string `bson:"ent,omitempty"` EntityType string `bson:"ent,omitempty"`
CreatedAt time.Time `bson:"created_at,omitempty"` CreatedAt time.Time `bson:"created_at,omitempty"`
UpdatedAt time.Time `bson:"updated_at,omitempty"` UpdatedAt time.Time `bson:"updated_at,omitempty"`
} }

View File

@ -16,7 +16,7 @@ import (
const USER_TYPE string = "user" const USER_TYPE string = "user"
type User struct { type User struct {
*model CommonFields `bson:"obj_info"`
mongoId primitive.ObjectID `bson:"_id,omitempty"` mongoId primitive.ObjectID `bson:"_id,omitempty"`
UserId string `bson:"user_id,omitempty"` UserId string `bson:"user_id,omitempty"`
Email string `bson:"email,omitempty"` Email string `bson:"email,omitempty"`
@ -28,18 +28,16 @@ func (user *User) Save(client *mongo.Client) error {
if user.mongoId.IsZero() { if user.mongoId.IsZero() {
now := time.Now() now := time.Now()
user.model = &model{ user.EntityType = USER_TYPE
EntityType: USER_TYPE, user.CreatedAt = now
CreatedAt: now, user.UpdatedAt = now
UpdatedAt: now,
}
user.UserId = uuid.New().String() user.UserId = uuid.New().String()
user.mongoId = primitive.NewObjectIDFromTimestamp(now) user.mongoId = primitive.NewObjectIDFromTimestamp(now)
} }
opts := options.Update().SetUpsert(true) opts := options.Update().SetUpsert(true)
res, err := client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).UpdateOne(context.Background(), user, opts) res, err := client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).UpdateOne(context.Background(), bson.M{"user_id": user.UserId}, bson.M{"$set": user},opts)
if err != nil { if err != nil {
return err return err
} }

View File

@ -58,7 +58,7 @@ func (db *DB) FindAllUsers() ([]models.User, error) {
conf := config.Config() conf := config.Config()
opts := options.Find() opts := options.Find()
res, err := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).Find(context.Background(), bson.M{"ent": models.USER_TYPE}, opts) res, err := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).Find(context.Background(), bson.M{"obj_info.ent": models.USER_TYPE}, opts)
if err != nil { if err != nil {
if err == mongo.ErrNoDocuments { if err == mongo.ErrNoDocuments {