JWT proto with login & registration
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
collection *mongo.Collection
|
||||
}
|
||||
|
||||
func NewRepository(db *mongo.Database) *Repository {
|
||||
return &Repository{
|
||||
collection: db.Collection("users"),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Repository) EnsureIndexes(ctx context.Context) error {
|
||||
_, err := r.collection.Indexes().CreateOne(ctx, mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "email", Value: 1}},
|
||||
Options: options.Index().SetUnique(true),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) Create(ctx context.Context, user *User) error {
|
||||
user.ID = bson.NewObjectID()
|
||||
user.CreatedAt = time.Now().UTC()
|
||||
_, err := r.collection.InsertOne(ctx, user)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) {
|
||||
var user User
|
||||
err := r.collection.FindOne(ctx, bson.M{"email": email}).Decode(&user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindByID(ctx context.Context, id bson.ObjectID) (*User, error) {
|
||||
var user User
|
||||
err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
Reference in New Issue
Block a user