cds-web/controllers/auth.go
rick 220611a563
small changes
add json for user
remove useless query in url for auth
update some go packages
2022-10-21 03:04:28 +02:00

102 lines
2.1 KiB
Go

package controllers
import (
"cds/dao"
"cds/models"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/shareed2k/goth_fiber"
"go.mongodb.org/mongo-driver/mongo"
)
func CheckAuth(c *fiber.Ctx) error {
token := c.Cookies("token", "")
if token == "" {
return c.SendStatus(fiber.StatusNotFound)
} else {
return c.SendStatus(fiber.StatusOK)
}
}
func Auth(c *fiber.Ctx) error {
provider, err := goth_fiber.GetProviderName(c)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": err,
})
}
var token string = ""
if provider == "discord" {
token, err = checkDiscord(c)
} else if provider == "steam" {
token, err = checkSteam(c)
}
if err == nil {
cookie := new(fiber.Cookie)
cookie.Name = "token"
cookie.Value = token
cookie.HTTPOnly = true
c.Cookie(cookie)
} else {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"ierror": fmt.Sprint(err),
})
}
//err = c.RedirectToRoute("index", fiber.Map{"auth": "ok"})
err = c.Redirect("/")
return err
//return c.SendStatus(fiber.StatusOK)
//return err
}
func checkDiscord(c *fiber.Ctx) (token string, err error) {
token = ""
gothuser, err := goth_fiber.CompleteUserAuth(c)
if err != nil {
return token, err
}
/*
fmt.Println(gothuser.UserID)
fmt.Println(gothuser.Name)
fmt.Println(gothuser.RawData["discriminator"])
fmt.Println(gothuser.AccessToken)
*/
id := gothuser.UserID
name := fmt.Sprint(gothuser.Name, "#", gothuser.RawData["discriminator"])
// on vérifie s'il existe déjà dans la db sinon on le créé
user, err := dao.GetByDiscord(id)
if err == mongo.ErrNoDocuments {
user = models.NewUserDiscord(id, name)
token, err = dao.CreateUser(user)
} else if err == nil {
token = user.Id.Hex()
}
return token, err
}
func checkSteam(c *fiber.Ctx) (token string, err error) {
token = ""
gothuser, err := goth_fiber.CompleteUserAuth(c)
if err != nil {
return token, err
}
id := gothuser.UserID
user, err := dao.GetBySteam(id)
if err == mongo.ErrNoDocuments {
user = models.NewUserSteam(id)
token, err = dao.CreateUser(user)
} else if err == nil {
token = user.Id.Hex()
}
return token, err
}