61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
|
package user
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
"log/slog"
|
||
|
|
||
|
"gitserver.in/patialtech/rano/db"
|
||
|
"gitserver.in/patialtech/rano/db/ent"
|
||
|
"gitserver.in/patialtech/rano/db/ent/verifytoken"
|
||
|
"gitserver.in/patialtech/rano/util/logger"
|
||
|
)
|
||
|
|
||
|
// VerifyEmailAddress by a token
|
||
|
func VerifyEmailAddress(ctx context.Context, token string) error {
|
||
|
// decode token
|
||
|
uid, err := tokenToVerifyEmail(token)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
client := db.Client()
|
||
|
|
||
|
// get token from DB
|
||
|
vt, err := client.VerifyToken.Query().Where(verifytoken.TokenEQ(token)).Only(ctx)
|
||
|
if err != nil {
|
||
|
if ent.IsNotFound(err) {
|
||
|
return ErrInvalidToken
|
||
|
}
|
||
|
|
||
|
logger.Error(err, slog.String("ref", "pkg/user/verify.VerifyEmail"))
|
||
|
return ErrInvalidToken
|
||
|
}
|
||
|
|
||
|
// all good, lets do the following
|
||
|
// 1. Update user email verify status
|
||
|
// 2. Remvoe token from DB
|
||
|
// do it in a transaction
|
||
|
|
||
|
tx, err := client.BeginTx(ctx, nil)
|
||
|
if err != nil {
|
||
|
logger.Error(err)
|
||
|
return errors.New("unexpected error")
|
||
|
}
|
||
|
|
||
|
// update user email verify status
|
||
|
if err = tx.User.UpdateOneID(uid).SetEmailVerified(true).Exec(ctx); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
// remove token from DB
|
||
|
if err = tx.VerifyToken.DeleteOneID(vt.ID).Exec(ctx); err != nil {
|
||
|
_ = tx.Rollback()
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
// we are all done now,
|
||
|
// let's commit
|
||
|
return tx.Commit()
|
||
|
}
|