Exemple #1
0
func (mongo *Mongo) Login(c *gin.Context) {

	var Incoming struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	err := c.BindJSON(&Incoming)

	if err != nil {
		println(err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"err": true,
			"msg": "Error parsing request.",
		})
		return
	}

	var t models.Teacher

	t.Username = Incoming.Username
	t.Password = Incoming.Password

	println("Got from user", Incoming.Username, t.Username, t.Password)

	teacher := t.GetByUsernameAndPassword(mongo.Database)

	if teacher.Subject != "" {
		/**
		Create the token
		*/
		token := jwt.New(jwt.SigningMethodHS256)
		token.Claims["username"] = teacher.Username
		token.Claims["subject"] = teacher.Subject
		token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		tokenString, err := token.SignedString([]byte(utils.MySigningKey))

		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"err": true,
				"msg": "Error occured while creating a token",
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"err":     false,
			"msg":     "Got",
			"teacher": teacher,
			"token":   tokenString,
		})
	} else {
		c.JSON(http.StatusInternalServerError, gin.H{
			"err": true,
			"msg": "Not found.",
		})
	}
}
Exemple #2
0
/**
Handler for new teacher
*/
func (mongo *Mongo) AddTeacher(c *gin.Context) {
	/**
	Room for imporv use auto bindind
	*/

	var teacher models.Teacher

	var req struct {
		AdminPass string `json:"adminPass"`
		Username  string `json:"username"`
		Password  string `json:"password"`
		Subject   string `json:"subject"`
	}

	err := c.BindJSON(&req)

	if err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "Could not parse")
		return
	}

	adminPass := req.AdminPass

	if adminPass == "admin" {

		teacher.Password = req.Password
		teacher.Subject = req.Subject
		teacher.Username = req.Username

		if teacher.Password == "" || teacher.Subject == "" || teacher.Username == "" {
			var res utils.Response
			res.Err = true
			res.Msg = "Missing params"

			c.JSON(http.StatusForbidden, res)
		} else {

			/**
			Insert the teacher in the db
			*/
			response := teacher.AddDoc(mongo.Database)

			if response.Err == true {
				c.JSON(http.StatusInternalServerError, response)
			} else {
				c.JSON(http.StatusOK, response)
			}
		}

	} else {
		var res utils.Response
		res.Err = true
		res.Msg = "Unauth "

		c.JSON(http.StatusForbidden, res)
	}
}