updated/student-update-password

This commit is contained in:
SowinskiBraeden committed 2022-01-14 23:08:38 -08:00
1 parent 17ceb974ff
commit 20fb1529ed
1 file changed
+92 -3
+92 -3
View File
@@ -2,8 +2,10 @@ package controllers
import (
"context"
"school-management/models"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gofiber/fiber/v2"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
@@ -196,9 +198,96 @@ func UpdateStudentHomeroom(c *fiber.Ctx) error {
}
func UpdateStudentPassword(c *fiber.Ctx) error {
return c.Status(fiber.StatusNotImplemented).JSON(fiber.Map{
"success": nil,
"message": "not implimented",
var data map[string]string
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
if err := c.BodyParser(&data); err != nil {
cancel()
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"success": false,
"message": "Failed to parse body",
"error": err,
})
}
cookie := c.Cookies("jwt")
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(SecretKey), nil
})
if err != nil {
cancel()
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"success": false,
"message": "not authorized",
})
}
claims := token.Claims.(*jwt.StandardClaims)
var student models.Student
findErr := studentCollection.FindOne(context.TODO(), bson.M{"sid": claims.Issuer}).Decode(&student)
if findErr != nil {
cancel()
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"success": false,
"message": "student not found",
})
}
// Check required fields are included
if data["currentPassword"] == "" || data["newPassword1"] == "" || data["newPassword2"] == "" {
cancel()
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"success": false,
"message": "missing required fields",
})
}
if student.ComparePasswords(data["currentPassword"]) {
cancel()
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"success": false,
"message": "Your current password is incorrect",
})
}
if data["newPassword1"] != data["newPassword2"] {
cancel()
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"success": false,
"message": "Your new password must match",
})
}
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
update := bson.M{
"$set": bson.M{
"password": student.HashPassword(data["newPassword1"]),
"temppassword": false, // If it were a temp password, its not now
"updated_at": update_time,
},
}
result, updateErr := studentCollection.UpdateOne(
ctx,
bson.M{"sid": data["sid"]},
update,
)
if updateErr != nil {
cancel()
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"success": false,
"message": "the student password could not be updated",
"error": updateErr,
})
}
defer cancel()
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"success": true,
"message": "successfully updated student password",
"result": result,
})
}