Example #1
0
func CreateAccount(c *echo.Context) error {
	logrus.Infof("create account")
	c.Request().ParseForm()
	cai := c.Request().Form
	a, err := validateCreateAccount(cai)
	if err != nil {
		logrus.Errorf("failed create account input validation %s", err.Error())
		c.JSON(400, Response{})
		return nil
	}
	db := c.Get("db").(*mgo.Database)
	_, err = models.LoadAccount(db, a.Username)
	if err == nil {
		logrus.Errorf("account taken: %s", a.Username)
		c.JSON(409, Response{})
		return nil
	} else if err != models.AccountNotFound && err != nil {
		logrus.Errorf("db error in create account: %s", err.Error())
		c.JSON(500, Response{})
		return nil
	}

	err = models.CreateAccount(db, a)
	if err != nil {
		logrus.Errorf("failed to create account: %s", err.Error())
		c.JSON(500, Response{})
		return nil
	}

	c.JSON(200, Response{true, a})
	return nil
}
Example #2
0
func Login(c *echo.Context) error {
	logrus.Infof("login")

	c.Request().ParseForm()
	li := c.Request().Form
	inputAccount, err := validateLogin(li)
	if err != nil {
		logrus.Errorf("failed login input validation: %s", err.Error())
		c.JSON(400, Response{})
		return nil
	}

	db := c.Get("db").(*mgo.Database)
	a, err := models.LoadAccount(db, inputAccount.Username)
	if err != nil {
		logrus.Errorf("failed to load account in login")
		c.JSON(500, Response{})
		return err
	}

	if err := bcrypt.CompareHashAndPassword([]byte(a.Hashword), []byte(inputAccount.Password)); err != nil {
		logrus.Errorf("failed to authenticate in login: %s", err.Error())
		c.JSON(401, Response{})
		return nil
	}

	sessionID, err := a.NewSession(db)
	if err != nil {
		logrus.Errorf("failed to create new session in login: %s", err.Error())
		c.JSON(500, Response{})
		return nil
	}

	resp := struct {
		SessionID string `json:"session_id"`
	}{sessionID}

	c.JSON(200, Response{
		Success: true,
		Payload: resp,
	})
	return nil
}