Skip to content

Commit

Permalink
Fix issues with login
Browse files Browse the repository at this point in the history
  • Loading branch information
rupinr committed Oct 28, 2024
1 parent 85fd34e commit 7f49223
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 57 deletions.
20 changes: 0 additions & 20 deletions Features.md

This file was deleted.

42 changes: 28 additions & 14 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"news-master/app"
"news-master/logger"
"news-master/repository"
"os"
"time"

Expand Down Expand Up @@ -111,36 +112,43 @@ func AuthMiddleware(validateToken func(Token) *DecodedUser) gin.HandlerFunc {

func ValidateJWT(tokenString string) (*DecodedUser, error) {
user := defaultDecodedUser()
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return publicKey, nil
})

if err != nil {
return user, err
logger.Log.Error("Error parsing token:", "error", err.Error())
return nil, err
}

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
user.Admin = false
user.Valid = true
user.Email = claims["email"].(string)
user.ID = uint(claims["id"].(float64))

user.Email = claims.Email
user.ID = claims.ID
resetLoginAttemptCounter(user.ID)
} else {
fmt.Println("Invalid token.")
logger.Log.Debug("Invalid token.")
}

return user, nil
}

func resetLoginAttemptCounter(userId uint) {
repository.ResetLoginCounter(userId)
}

func SubscriberToken(id uint, email string, validityInHours int) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"email": email,
"exp": time.Now().Add(time.Duration(validityInHours) * time.Hour).Unix(),
"id": id,
})
claims := CustomClaims{
email,
id,
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(validityInHours) * time.Hour)),
Issuer: "api",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tokenString, err := token.SignedString(privateKey)
if err != nil {
return "", err
Expand All @@ -154,3 +162,9 @@ func User(c *gin.Context) *DecodedUser {
user := contextUser.(*DecodedUser)
return user
}

type CustomClaims struct {
Email string `json:"Email"`
ID uint `json:"id"`
jwt.RegisteredClaims
}
13 changes: 10 additions & 3 deletions repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ func GetAllSites() []entity.Site {
return sites
}

func CreateUser(userData dto.User) entity.User {
func CreateUser(userData dto.User) (entity.User, bool, error) {
userDb := entity.User{Email: userData.Email}
var user entity.User
db().Where(userDb).FirstOrCreate(&user, userDb)
return user
r := db().Where(userDb).FirstOrCreate(&user, userDb)
return user, r.RowsAffected == 1, r.Error
}

func MarkUserDeleted(email string) {
Expand All @@ -126,6 +126,13 @@ func MarkUserDeleted(email string) {
})
}

func ResetLoginCounter(id uint) {
user := entity.User{}
db().Find(&user, id)
user.LoginAttemptCount = 0
db().Save(&user)
}

func GetUser(userData dto.User) entity.User {
userDb := entity.User{Email: userData.Email}
var user entity.User
Expand Down
43 changes: 24 additions & 19 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,18 @@ import (
)

func CreateUserAndTriggerLoginEmail(user dto.User) (entity.User, error) {
createdUser := repository.CreateUser(user)
createdUser, isNewUser, createErr := repository.CreateUser(user)
maxLoginAttempt, _ := strconv.Atoi(app.Config.MaxLoginAttempt)
if createdUser.LoginAttemptCount < maxLoginAttempt {
repository.IncrementAndGetLoginAttempt(user)
if isNewUser {
createSubscriptionSchedule(createdUser)
}
token, _ := auth.SubscriberToken(createdUser.ID, user.Email, 24)
defaultValue := true
subscriptionSchedule := repository.CreateSubscriptionSchedule(
dto.SubscriptionSchedule{
DailyFrequency: dto.DailyFrequency{
Monday: &defaultValue,
Tuesday: &defaultValue,
Wednesday: &defaultValue,
Thursday: &defaultValue,
Friday: &defaultValue,
Saturday: &defaultValue,
Sunday: &defaultValue,
},
TimeSlot: common.Morning,
},
)
repository.CreateSubscription(createdUser, []string{}, subscriptionSchedule.ID, false)

emailData := email.EmailData{ActivationLink: helper.PreAuthLink(token)}
htmlEmail, htmlErr := email.GenerateRegistrationHTML(emailData)
textEmail, txtErr := email.GenerateText(emailData)
if htmlErr == nil && txtErr == nil {
if htmlErr == nil && txtErr == nil && createErr == nil {
go email.SendEmail(
createdUser.Email,
"Activate Your QuickBrew Subscription Now!",
Expand All @@ -57,6 +43,25 @@ func CreateUserAndTriggerLoginEmail(user dto.User) (entity.User, error) {

}

func createSubscriptionSchedule(user entity.User) {
defaultValue := true
subscriptionSchedule := repository.CreateSubscriptionSchedule(
dto.SubscriptionSchedule{
DailyFrequency: dto.DailyFrequency{
Monday: &defaultValue,
Tuesday: &defaultValue,
Wednesday: &defaultValue,
Thursday: &defaultValue,
Friday: &defaultValue,
Saturday: &defaultValue,
Sunday: &defaultValue,
},
TimeSlot: common.Morning,
},
)
repository.CreateSubscription(user, []string{}, subscriptionSchedule.ID, false)
}

func CreateFeedBackAndTriggerAdminEmail(feedback dto.Feedback) {
createdFeedback, err := repository.CreateFeedBack(feedback)
if err == nil {
Expand Down
2 changes: 1 addition & 1 deletion tasks/tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func SendNewsletter() {
continue
}

token, tokenErr := auth.SubscriberToken(subscription.UserID, subscription.User.Email, 24*7)
token, tokenErr := auth.SubscriberToken(subscription.UserID, subscription.User.Email, 24*30) //30 days

if tokenErr != nil {
logger.Log.Error("Error generating token for email", "error", tokenErr.Error())
Expand Down

0 comments on commit 7f49223

Please sign in to comment.