85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
package users
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"acooldomain.co/backend/auth"
|
|
"acooldomain.co/backend/mail"
|
|
"acooldomain.co/backend/models"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
)
|
|
|
|
type Connection struct {
|
|
connection *mongo.Client
|
|
}
|
|
|
|
func (con Connection) GetUsers(c *gin.Context) {
|
|
users, err := con.connection.Database("Backend").Collection("Users").Find(context.TODO(), bson.D{})
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
var response []models.User
|
|
|
|
err = users.All(context.TODO(), &response)
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
c.IndentedJSON(http.StatusOK, response)
|
|
}
|
|
|
|
type UserResponse struct {
|
|
Username string
|
|
Permissions models.Permission
|
|
Email string
|
|
}
|
|
|
|
func (con Connection) GetUser(c *gin.Context) {
|
|
claims, exists := c.Get("claims")
|
|
if !exists {
|
|
c.AbortWithStatus(505)
|
|
return
|
|
}
|
|
|
|
c.IndentedJSON(http.StatusOK, UserResponse{
|
|
Username: claims.(*auth.AuthClaims).Username,
|
|
Permissions: claims.(*auth.AuthClaims).Permissions,
|
|
})
|
|
}
|
|
|
|
type InviteUser struct {
|
|
Email string `json:"Email"`
|
|
Permissions models.Permission `json:"Permissions"`
|
|
}
|
|
|
|
func (con Connection) InviteUser(c *gin.Context) {
|
|
var request InviteUser
|
|
json.NewDecoder(c.Request.Body).Decode(&request)
|
|
token := uuid.NewString()
|
|
|
|
err := mail.SendMail(request.Email, "You've been invited to join", "please open this link https://games.acooldomain.co/signup?token="+token)
|
|
if err != nil {
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
con.connection.Database("Backend").Collection("Tokens").InsertOne(context.TODO(), auth.InviteToken{
|
|
Email: request.Email,
|
|
Permissions: request.Permissions,
|
|
Token: token,
|
|
})
|
|
c.JSON(200, "OK")
|
|
}
|
|
|
|
func LoadGroup(group *gin.RouterGroup, client *mongo.Client, config models.GlobalConfig) {
|
|
connection := Connection{connection: client}
|
|
group.GET("/", auth.AuthorizedTo(0), connection.GetUsers)
|
|
group.GET("/@me", auth.AuthorizedTo(0), connection.GetUser)
|
|
group.POST("/", auth.AuthorizedTo(models.Admin), connection.InviteUser)
|
|
}
|