Exemple #1
0
// ValidateUser checks if the request triggered by a valid user
func (b *BaseAPI) ValidateUser() int {

	username, password, ok := b.Ctx.Request.BasicAuth()
	if ok {
		log.Infof("Requst with Basic Authentication header, username: %s", username)
		user, err := auth.Login(models.AuthModel{
			Principal: username,
			Password:  password,
		})
		if err != nil {
			log.Errorf("Error while trying to login, username: %s, error: %v", username, err)
			user = nil
		}
		if user != nil {
			return user.UserID
		}
	}
	sessionUserID := b.GetSession("userId")
	if sessionUserID == nil {
		log.Warning("No user id in session, canceling request")
		b.CustomAbort(http.StatusUnauthorized, "")
	}
	userID := sessionUserID.(int)
	u, err := dao.GetUser(models.User{UserID: userID})
	if err != nil {
		log.Errorf("Error occurred in GetUser, error: %v", err)
		b.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if u == nil {
		log.Warningf("User was deleted already, user id: %d, canceling request.", userID)
		b.CustomAbort(http.StatusUnauthorized, "")
	}
	return userID
}
Exemple #2
0
//GetTopRepos handles request GET /api/repositories/top
func (ra *RepositoryAPI) GetTopRepos() {
	var err error
	var countNum int
	count := ra.GetString("count")
	if len(count) == 0 {
		countNum = 10
	} else {
		countNum, err = strconv.Atoi(count)
		if err != nil {
			log.Errorf("Get parameters error--count, err: %v", err)
			ra.CustomAbort(http.StatusBadRequest, "bad request of count")
		}
		if countNum <= 0 {
			log.Warning("count must be a positive integer")
			ra.CustomAbort(http.StatusBadRequest, "count is 0 or negative")
		}
	}
	repos, err := dao.GetTopRepos(countNum)
	if err != nil {
		log.Errorf("error occured in get top 10 repos: %v", err)
		ra.CustomAbort(http.StatusInternalServerError, "internal server error")
	}
	ra.Data["json"] = repos
	ra.ServeJSON()
}
Exemple #3
0
// Post ...
func (ua *UserAPI) Post() {

	if !(ua.AuthMode == "db_auth") {
		ua.CustomAbort(http.StatusForbidden, "")
	}

	if !(ua.SelfRegistration || ua.IsAdmin) {
		log.Warning("Registration can only be used by admin role user when self-registration is off.")
		ua.CustomAbort(http.StatusForbidden, "")
	}

	user := models.User{}
	ua.DecodeJSONReq(&user)
	err := validate(user)
	if err != nil {
		log.Warning("Bad request in Register: %v", err)
		ua.RenderError(http.StatusBadRequest, "register error:"+err.Error())
		return
	}
	userExist, err := dao.UserExists(user, "username")
	if err != nil {
		log.Errorf("Error occurred in Register: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if userExist {
		log.Warning("username has already been used!")
		ua.RenderError(http.StatusConflict, "username has already been used!")
		return
	}
	emailExist, err := dao.UserExists(user, "email")
	if err != nil {
		log.Errorf("Error occurred in change user profile: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if emailExist {
		log.Warning("email has already been used!")
		ua.RenderError(http.StatusConflict, "email has already been used!")
		return
	}
	userID, err := dao.Register(user)
	if err != nil {
		log.Errorf("Error occurred in Register: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}

	ua.Redirect(http.StatusCreated, strconv.FormatInt(userID, 10))
}
Exemple #4
0
// Put ...
func (ua *UserAPI) Put() {
	ldapAdminUser := (ua.AuthMode == "ldap_auth" && ua.userID == 1 && ua.userID == ua.currentUserID)

	if !(ua.AuthMode == "db_auth" || ldapAdminUser) {
		ua.CustomAbort(http.StatusForbidden, "")
	}
	if !ua.IsAdmin {
		if ua.userID != ua.currentUserID {
			log.Warning("Guests can only change their own account.")
			ua.CustomAbort(http.StatusForbidden, "Guests can only change their own account.")
		}
	}
	user := models.User{UserID: ua.userID}
	ua.DecodeJSONReq(&user)
	err := commonValidate(user)
	if err != nil {
		log.Warning("Bad request in change user profile: %v", err)
		ua.RenderError(http.StatusBadRequest, "change user profile error:"+err.Error())
		return
	}
	userQuery := models.User{UserID: ua.userID}
	u, err := dao.GetUser(userQuery)
	if err != nil {
		log.Errorf("Error occurred in GetUser, error: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if u == nil {
		log.Errorf("User with Id: %d does not exist", ua.userID)
		ua.CustomAbort(http.StatusNotFound, "")
	}
	if u.Email != user.Email {
		emailExist, err := dao.UserExists(user, "email")
		if err != nil {
			log.Errorf("Error occurred in change user profile: %v", err)
			ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		if emailExist {
			log.Warning("email has already been used!")
			ua.RenderError(http.StatusConflict, "email has already been used!")
			return
		}
	}
	if err := dao.ChangeUserProfile(user); err != nil {
		log.Errorf("Failed to update user profile, error: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, err.Error())
	}
}
Exemple #5
0
// Get renders the Sign In page, it only works if the auth mode is set to db_auth
func (ac *AddUserController) Get() {

	if !ac.IsAdmin {
		log.Warning("Add user can only be used by admin role user.")
		ac.Redirect("/signIn", http.StatusFound)
	}

	if ac.AuthMode == "db_auth" {
		ac.ForwardTo("page_title_add_user", "register")
	} else {
		ac.Redirect("/signIn", http.StatusFound)
	}
}
Exemple #6
0
// Get renders the Sign In page, it only works if the auth mode is set to db_auth
func (rc *RegisterController) Get() {

	if !rc.SelfRegistration {
		log.Warning("Registration is disabled when self-registration is off.")
		rc.Redirect("/signIn", http.StatusFound)
	}

	if rc.AuthMode == "db_auth" {
		rc.ForwardTo("page_title_registration", "register")
	} else {
		rc.Redirect("/signIn", http.StatusFound)
	}
}
Exemple #7
0
//Get returns the recent logs according to parameters
func (l *LogAPI) Get() {
	var err error
	startTime := l.GetString("start_time")
	if len(startTime) != 0 {
		i, err := strconv.ParseInt(startTime, 10, 64)
		if err != nil {
			log.Errorf("Parse startTime to int error, err: %v", err)
			l.CustomAbort(http.StatusBadRequest, "startTime is not a valid integer")
		}
		startTime = time.Unix(i, 0).String()
	}

	endTime := l.GetString("end_time")
	if len(endTime) != 0 {
		j, err := strconv.ParseInt(endTime, 10, 64)
		if err != nil {
			log.Errorf("Parse endTime to int error, err: %v", err)
			l.CustomAbort(http.StatusBadRequest, "endTime is not a valid integer")
		}
		endTime = time.Unix(j, 0).String()
	}

	var linesNum int
	lines := l.GetString("lines")
	if len(lines) != 0 {
		linesNum, err = strconv.Atoi(lines)
		if err != nil {
			log.Errorf("Get parameters error--lines, err: %v", err)
			l.CustomAbort(http.StatusBadRequest, "bad request of lines")
		}
		if linesNum <= 0 {
			log.Warning("lines must be a positive integer")
			l.CustomAbort(http.StatusBadRequest, "lines is 0 or negative")
		}
	} else if len(startTime) == 0 && len(endTime) == 0 {
		linesNum = 10
	}

	var logList []models.AccessLog
	logList, err = dao.GetRecentLogs(l.userID, linesNum, startTime, endTime)
	if err != nil {
		log.Errorf("Get recent logs error, err: %v", err)
		l.CustomAbort(http.StatusInternalServerError, "Internal error")
	}
	l.Data["json"] = logList
	l.ServeJSON()
}
Exemple #8
0
// ChangePassword handles PUT to /api/users/{}/password
func (ua *UserAPI) ChangePassword() {
	ldapAdminUser := (ua.AuthMode == "ldap_auth" && ua.userID == 1 && ua.userID == ua.currentUserID)

	if !(ua.AuthMode == "db_auth" || ldapAdminUser) {
		ua.CustomAbort(http.StatusForbidden, "")
	}

	if !ua.IsAdmin {
		if ua.userID != ua.currentUserID {
			log.Error("Guests can only change their own account.")
			ua.CustomAbort(http.StatusForbidden, "Guests can only change their own account.")
		}
	}

	var req passwordReq
	ua.DecodeJSONReq(&req)
	if req.OldPassword == "" {
		log.Error("Old password is blank")
		ua.CustomAbort(http.StatusBadRequest, "Old password is blank")
	}

	queryUser := models.User{UserID: ua.userID, Password: req.OldPassword}
	user, err := dao.CheckUserPassword(queryUser)
	if err != nil {
		log.Errorf("Error occurred in CheckUserPassword: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if user == nil {
		log.Warning("Password input is not correct")
		ua.CustomAbort(http.StatusForbidden, "old_password_is_not_correct")
	}

	if req.NewPassword == "" {
		ua.CustomAbort(http.StatusBadRequest, "please_input_new_password")
	}
	updateUser := models.User{UserID: ua.userID, Password: req.NewPassword, Salt: user.Salt}
	err = dao.ChangeUserPassword(updateUser, req.OldPassword)
	if err != nil {
		log.Errorf("Error occurred in ChangeUserPassword: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
}
Exemple #9
0
// CheckUserPassword checks whether the password is correct.
func CheckUserPassword(query models.User) (*models.User, error) {

	currentUser, err := GetUser(query)

	if err != nil {
		return nil, err
	}

	if currentUser == nil {
		return nil, nil
	}

	sql := `select user_id, username, salt from user where deleted = 0`

	queryParam := make([]interface{}, 1)

	if query.UserID != 0 {
		sql += ` and password = ? and user_id = ?`
		queryParam = append(queryParam, utils.Encrypt(query.Password, currentUser.Salt))
		queryParam = append(queryParam, query.UserID)
	} else {
		sql += ` and username = ? and password = ?`
		queryParam = append(queryParam, currentUser.Username)
		queryParam = append(queryParam, utils.Encrypt(query.Password, currentUser.Salt))
	}
	o := GetOrmer()
	var user []models.User

	n, err := o.Raw(sql, queryParam).QueryRows(&user)

	if err != nil {
		return nil, err
	}

	if n == 0 {
		log.Warning("User principal does not match password. Current:", currentUser)
		return nil, nil
	}

	return &user[0], nil
}