Example #1
0
func DeleteUser(ctx *middleware.Context) {
	uid := com.StrTo(ctx.Params(":userid")).MustInt64()
	if uid == 0 {
		ctx.Handle(404, "DeleteUser", nil)
		return
	}

	u, err := models.GetUserById(uid)
	if err != nil {
		ctx.Handle(500, "GetUserById", err)
		return
	}

	if err = models.DeleteUser(u); err != nil {
		switch err {
		case models.ErrUserOwnRepos:
			ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo"))
			ctx.Redirect("/admin/users/" + ctx.Params(":userid"))
		default:
			ctx.Handle(500, "DeleteUser", err)
		}
		return
	}
	log.Trace("Account deleted by admin(%s): %s", ctx.User.Name, u.Name)
	ctx.Redirect("/admin/users")
}
Example #2
0
func Dashboard(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("admin.dashboard")
	ctx.Data["PageIsAdmin"] = true
	ctx.Data["PageIsAdminDashboard"] = true

	// Run operation.
	op, _ := com.StrTo(ctx.Query("op")).Int()
	if op > 0 {
		var err error
		var success string

		switch AdminOperation(op) {
		case CLEAN_UNBIND_OAUTH:
			success = "All unbind OAuthes have been deleted."
			err = models.CleanUnbindOauth()
		case CLEAN_INACTIVATE_USER:
			success = "All inactivate accounts have been deleted."
			err = models.DeleteInactivateUsers()
		}

		if err != nil {
			ctx.Flash.Error(err.Error())
		} else {
			ctx.Flash.Success(success)
		}
		ctx.Redirect("/admin")
		return
	}

	ctx.Data["Stats"] = models.GetStatistic()
	updateSystemStatus()
	ctx.Data["SysStatus"] = sysStatus
	ctx.HTML(200, DASHBOARD)
}
Example #3
0
func SettingsPasswordPost(ctx *middleware.Context, form auth.ChangePasswordForm) {
	ctx.Data["Title"] = ctx.Tr("settings")
	ctx.Data["PageIsUserSettings"] = true
	ctx.Data["PageIsSettingsPassword"] = true

	if ctx.HasError() {
		ctx.HTML(200, SETTINGS_PASSWORD)
		return
	}

	tmpUser := &models.User{
		Passwd: form.OldPassword,
		Salt:   ctx.User.Salt,
	}
	tmpUser.EncodePasswd()
	if ctx.User.Passwd != tmpUser.Passwd {
		ctx.Flash.Error(ctx.Tr("settings.password_incorrect"))
	} else if form.Password != form.Retype {
		ctx.Flash.Error(ctx.Tr("form.password_not_match"))
	} else {
		ctx.User.Passwd = form.Password
		ctx.User.Salt = models.GetUserSalt()
		ctx.User.EncodePasswd()
		if err := models.UpdateUser(ctx.User); err != nil {
			ctx.Handle(500, "UpdateUser", err)
			return
		}
		log.Trace("User password updated: %s", ctx.User.Name)
		ctx.Flash.Success(ctx.Tr("settings.change_password_success"))
	}

	ctx.Redirect("/user/settings/password")
}
Example #4
0
func DeleteAuthSource(ctx *middleware.Context) {
	id := com.StrTo(ctx.Params(":authid")).MustInt64()
	if id == 0 {
		ctx.Handle(404, "DeleteAuthSource", nil)
		return
	}

	a, err := models.GetLoginSourceById(id)
	if err != nil {
		ctx.Handle(500, "GetLoginSourceById", err)
		return
	}

	if err = models.DelLoginSource(a); err != nil {
		switch err {
		case models.ErrAuthenticationUserUsed:
			ctx.Flash.Error("form.still_own_user")
			ctx.Redirect("/admin/auths/" + ctx.Params(":authid"))
		default:
			ctx.Handle(500, "DelLoginSource", err)
		}
		return
	}
	log.Trace("Authentication deleted by admin(%s): %s", ctx.User.Name, a.Name)
	ctx.Redirect("/admin/auths")
}
Example #5
0
func SettingsDelete(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("settings")
	ctx.Data["PageIsUserSettings"] = true
	ctx.Data["PageIsSettingsDelete"] = true

	if ctx.Req.Method == "POST" {
		// tmpUser := models.User{
		// 	Passwd: ctx.Query("password"),
		// 	Salt:   ctx.User.Salt,
		// }
		// tmpUser.EncodePasswd()
		// if tmpUser.Passwd != ctx.User.Passwd {
		// 	ctx.Flash.Error("Password is not correct. Make sure you are owner of this account.")
		// } else {
		if err := models.DeleteUser(ctx.User); err != nil {
			switch err {
			case models.ErrUserOwnRepos:
				ctx.Flash.Error(ctx.Tr("form.still_own_repo"))
				ctx.Redirect("/user/settings/delete")
			default:
				ctx.Handle(500, "DeleteUser", err)
			}
		} else {
			log.Trace("Account deleted: %s", ctx.User.Name)
			ctx.Redirect("/")
		}
		return
	}

	ctx.HTML(200, SETTINGS_DELETE)
}
Example #6
0
func SettingsSocial(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("settings")
	ctx.Data["PageIsUserSettings"] = true
	ctx.Data["PageIsSettingsSocial"] = true

	// Unbind social account.
	remove, _ := com.StrTo(ctx.Query("remove")).Int64()
	if remove > 0 {
		if err := models.DeleteOauth2ById(remove); err != nil {
			ctx.Handle(500, "DeleteOauth2ById", err)
			return
		}
		ctx.Flash.Success(ctx.Tr("settings.unbind_success"))
		ctx.Redirect("/user/settings/social")
		return
	}

	socials, err := models.GetOauthByUserId(ctx.User.Id)
	if err != nil {
		ctx.Handle(500, "GetOauthByUserId", err)
		return
	}
	ctx.Data["Socials"] = socials
	ctx.HTML(200, SETTINGS_SOCIAL)
}
Example #7
0
func Home(ctx *middleware.Context) {
	if ctx.IsSigned {
		if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
			ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
			ctx.HTML(200, user.ACTIVATE)
		} else {
			user.Dashboard(ctx)
		}
		return
	}

	// Check auto-login.
	uname := ctx.GetCookie(setting.CookieUserName)
	if len(uname) != 0 {
		ctx.Redirect("/user/login")
		return
	}

	if setting.OauthService != nil {
		ctx.Data["OauthEnabled"] = true
		ctx.Data["OauthService"] = setting.OauthService
	}

	ctx.Data["PageIsHome"] = true
	ctx.HTML(200, HOME)
}
Example #8
0
func EditAuthSourcePost(ctx *middleware.Context, form auth.AuthenticationForm) {
	ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
	ctx.Data["PageIsAdmin"] = true
	ctx.Data["PageIsAdminAuthentications"] = true
	ctx.Data["PageIsAuths"] = true
	ctx.Data["LoginTypes"] = models.LoginTypes
	ctx.Data["SMTPAuths"] = models.SMTPAuths

	if ctx.HasError() {
		ctx.HTML(200, AUTH_EDIT)
		return
	}

	var config core.Conversion
	switch models.LoginType(form.Type) {
	case models.LDAP:
		config = &models.LDAPConfig{
			Ldapsource: ldap.Ldapsource{
				Host:         form.Host,
				Port:         form.Port,
				UseSSL:       form.UseSSL,
				BaseDN:       form.BaseDN,
				Attributes:   form.Attributes,
				Filter:       form.Filter,
				MsAdSAFormat: form.MsAdSA,
				Enabled:      true,
				Name:         form.AuthName,
			},
		}
	case models.SMTP:
		config = &models.SMTPConfig{
			Auth: form.SmtpAuth,
			Host: form.SmtpHost,
			Port: form.SmtpPort,
			TLS:  form.Tls,
		}
	default:
		ctx.Error(400)
		return
	}

	u := models.LoginSource{
		Id:                form.Id,
		Name:              form.AuthName,
		IsActived:         form.IsActived,
		Type:              models.LoginType(form.Type),
		AllowAutoRegister: form.AllowAutoRegister,
		Cfg:               config,
	}

	if err := models.UpdateSource(&u); err != nil {
		ctx.Handle(500, "UpdateSource", err)
		return
	}

	log.Trace("Authentication changed by admin(%s): %s", ctx.User.Name, form.AuthName)
	ctx.Flash.Success(ctx.Tr("admin.auths.update_success"))
	ctx.Redirect("/admin/auths/" + ctx.Params(":authid"))
}
Example #9
0
func SignInPost(ctx *middleware.Context, form auth.SignInForm) {
	ctx.Data["Title"] = ctx.Tr("sign_in")

	sid, isOauth := ctx.Session.Get("socialId").(int64)
	if isOauth {
		ctx.Data["IsSocialLogin"] = true
	} else if setting.OauthService != nil {
		ctx.Data["OauthEnabled"] = true
		ctx.Data["OauthService"] = setting.OauthService
	}

	if ctx.HasError() {
		ctx.HTML(200, SIGNIN)
		return
	}

	u, err := models.UserSignIn(form.UserName, form.Password)
	if err != nil {
		if err == models.ErrUserNotExist {
			ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), SIGNIN, &form)
		} else {
			ctx.Handle(500, "UserSignIn", err)
		}
		return
	}

	if form.Remember {
		days := 86400 * setting.LogInRememberDays
		ctx.SetCookie(setting.CookieUserName, u.Name, days)
		ctx.SetSuperSecureCookie(base.EncodeMd5(u.Rands+u.Passwd),
			setting.CookieRememberName, u.Name, days)
	}

	// Bind with social account.
	if isOauth {
		if err = models.BindUserOauth2(u.Id, sid); err != nil {
			if err == models.ErrOauth2RecordNotExist {
				ctx.Handle(404, "GetOauth2ById", err)
			} else {
				ctx.Handle(500, "GetOauth2ById", err)
			}
			return
		}
		ctx.Session.Delete("socialId")
		log.Trace("%s OAuth binded: %s -> %d", ctx.Req.RequestURI, form.UserName, sid)
	}

	ctx.Session.Set("uid", u.Id)
	ctx.Session.Set("uname", u.Name)
	if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
		ctx.SetCookie("redirect_to", "", -1)
		ctx.Redirect(redirectTo)
		return
	}

	ctx.Redirect("/")
}
Example #10
0
func SignIn(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("sign_in")

	if _, ok := ctx.Session.Get("socialId").(int64); ok {
		ctx.Data["IsSocialLogin"] = true
		ctx.HTML(200, SIGNIN)
		return
	}

	if setting.OauthService != nil {
		ctx.Data["OauthEnabled"] = true
		ctx.Data["OauthService"] = setting.OauthService
	}

	// Check auto-login.
	uname := ctx.GetCookie(setting.CookieUserName)
	if len(uname) == 0 {
		ctx.HTML(200, SIGNIN)
		return
	}

	isSucceed := false
	defer func() {
		if !isSucceed {
			log.Trace("auto-login cookie cleared: %s", uname)
			ctx.SetCookie(setting.CookieUserName, "", -1)
			ctx.SetCookie(setting.CookieRememberName, "", -1)
			return
		}
	}()

	u, err := models.GetUserByName(uname)
	if err != nil {
		if err != models.ErrUserNotExist {
			ctx.Handle(500, "GetUserByName", err)
		}
		return
	}

	if val, _ := ctx.GetSuperSecureCookie(
		base.EncodeMd5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
		ctx.HTML(200, SIGNIN)
		return
	}

	isSucceed = true

	ctx.Session.Set("uid", u.Id)
	ctx.Session.Set("uname", u.Name)
	if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
		ctx.SetCookie("redirect_to", "", -1)
		ctx.Redirect(redirectTo)
		return
	}

	ctx.Redirect("/")
}
Example #11
0
func NewAuthSourcePost(ctx *middleware.Context, form auth.AuthenticationForm) {
	ctx.Data["Title"] = ctx.Tr("admin.auths.new")
	ctx.Data["PageIsAdmin"] = true
	ctx.Data["PageIsAdminAuthentications"] = true
	ctx.Data["LoginTypes"] = models.LoginTypes
	ctx.Data["SMTPAuths"] = models.SMTPAuths

	if ctx.HasError() {
		ctx.HTML(200, AUTH_NEW)
		return
	}

	var u core.Conversion
	switch models.LoginType(form.Type) {
	case models.LDAP:
		u = &models.LDAPConfig{
			Ldapsource: ldap.Ldapsource{
				Host:         form.Host,
				Port:         form.Port,
				UseSSL:       form.UseSSL,
				BaseDN:       form.BaseDN,
				Attributes:   form.Attributes,
				Filter:       form.Filter,
				MsAdSAFormat: form.MsAdSA,
				Enabled:      true,
				Name:         form.AuthName,
			},
		}
	case models.SMTP:
		u = &models.SMTPConfig{
			Auth: form.SmtpAuth,
			Host: form.SmtpHost,
			Port: form.SmtpPort,
			TLS:  form.Tls,
		}
	default:
		ctx.Error(400)
		return
	}

	var source = &models.LoginSource{
		Type:              models.LoginType(form.Type),
		Name:              form.AuthName,
		IsActived:         true,
		AllowAutoRegister: form.AllowAutoRegister,
		Cfg:               u,
	}

	if err := models.CreateSource(source); err != nil {
		ctx.Handle(500, "CreateSource", err)
		return
	}

	log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, form.AuthName)
	ctx.Redirect("/admin/auths")
}
Example #12
0
func SignOut(ctx *middleware.Context) {
	ctx.Session.Delete("uid")
	ctx.Session.Delete("uname")
	ctx.Session.Delete("socialId")
	ctx.Session.Delete("socialName")
	ctx.Session.Delete("socialEmail")
	ctx.SetCookie(setting.CookieUserName, "", -1)
	ctx.SetCookie(setting.CookieRememberName, "", -1)
	ctx.Redirect("/")
}
Example #13
0
func Email2User(ctx *middleware.Context) {
	u, err := models.GetUserByEmail(ctx.Query("email"))
	if err != nil {
		if err == models.ErrUserNotExist {
			ctx.Handle(404, "user.Email2User(GetUserByEmail)", err)
		} else {
			ctx.Handle(500, "user.Email2User(GetUserByEmail)", err)
		}
		return
	}
	ctx.Redirect("/user/" + u.Name)
}
Example #14
0
func NewUserPost(ctx *middleware.Context, form auth.RegisterForm) {
	ctx.Data["Title"] = ctx.Tr("admin.users.new_account")
	ctx.Data["PageIsAdmin"] = true
	ctx.Data["PageIsAdminUsers"] = true

	if ctx.HasError() {
		ctx.HTML(200, USER_NEW)
		return
	}

	if form.Password != form.Retype {
		ctx.Data["Err_Password"] = true
		ctx.RenderWithErr(ctx.Tr("form.password_not_match"), USER_NEW, &form)
		return
	}

	u := &models.User{
		Name:      form.UserName,
		Email:     form.Email,
		Passwd:    form.Password,
		IsActive:  true,
		LoginType: models.PLAIN,
	}

	if len(form.LoginType) > 0 {
		// NOTE: need rewrite.
		fields := strings.Split(form.LoginType, "-")
		tp, _ := com.StrTo(fields[0]).Int()
		u.LoginType = models.LoginType(tp)
		u.LoginSource, _ = com.StrTo(fields[1]).Int64()
		u.LoginName = form.LoginName
	}

	if err := models.CreateUser(u); err != nil {
		switch err {
		case models.ErrUserAlreadyExist:
			ctx.Data["Err_UserName"] = true
			ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), USER_NEW, &form)
		case models.ErrEmailAlreadyUsed:
			ctx.Data["Err_Email"] = true
			ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_NEW, &form)
		case models.ErrUserNameIllegal:
			ctx.Data["Err_UserName"] = true
			ctx.RenderWithErr(ctx.Tr("form.illegal_username"), USER_NEW, &form)
		default:
			ctx.Handle(500, "CreateUser", err)
		}
		return
	}
	log.Trace("Account created by admin(%s): %s", ctx.User.Name, u.Name)
	ctx.Redirect("/admin/users")
}
Example #15
0
func Profile(ctx *middleware.Context) {
	ctx.Data["Title"] = "Profile"
	ctx.Data["PageIsUserProfile"] = true

	uname := ctx.Params(":username")
	// Special handle for FireFox requests favicon.ico.
	if uname == "favicon.ico" {
		ctx.Redirect("/img/favicon.png")
		return
	}

	u, err := models.GetUserByName(uname)
	if err != nil {
		if err == models.ErrUserNotExist {
			ctx.Handle(404, "GetUserByName", err)
		} else {
			ctx.Handle(500, "GetUserByName", err)
		}
		return
	}

	if u.IsOrganization() {
		ctx.Redirect("/org/" + u.Name)
		return
	}

	// For security reason, hide e-mail address for anonymous visitors.
	if !ctx.IsSigned {
		u.Email = ""
	}
	ctx.Data["Owner"] = u

	tab := ctx.Query("tab")
	ctx.Data["TabName"] = tab
	switch tab {
	case "activity":
		ctx.Data["Feeds"], err = models.GetFeeds(u.Id, 0, true)
		if err != nil {
			ctx.Handle(500, "GetFeeds", err)
			return
		}
	default:
		ctx.Data["Repos"], err = models.GetRepositories(u.Id, ctx.IsSigned && ctx.User.Id == u.Id)
		if err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	}

	ctx.HTML(200, PROFILE)
}
Example #16
0
func Activate(ctx *middleware.Context) {
	code := ctx.Query("code")
	if len(code) == 0 {
		ctx.Data["IsActivatePage"] = true
		if ctx.User.IsActive {
			ctx.Error(404)
			return
		}
		// Resend confirmation e-mail.
		if setting.Service.RegisterEmailConfirm {
			if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
				ctx.Data["ResendLimited"] = true
			} else {
				ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
				mailer.SendActiveMail(ctx.Render, ctx.User)

				if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
					log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
				}
			}
		} else {
			ctx.Data["ServiceNotEnabled"] = true
		}
		ctx.HTML(200, ACTIVATE)
		return
	}

	// Verify code.
	if user := models.VerifyUserActiveCode(code); user != nil {
		user.IsActive = true
		user.Rands = models.GetUserSalt()
		if err := models.UpdateUser(user); err != nil {
			if err == models.ErrUserNotExist {
				ctx.Error(404)
			} else {
				ctx.Handle(500, "UpdateUser", err)
			}
			return
		}

		log.Trace("User activated: %s", user.Name)

		ctx.Session.Set("uid", user.Id)
		ctx.Session.Set("uname", user.Name)
		ctx.Redirect("/")
		return
	}

	ctx.Data["IsActivateFailed"] = true
	ctx.HTML(200, ACTIVATE)
}
Example #17
0
func EditUserPost(ctx *middleware.Context, form auth.AdminEditUserForm) {
	ctx.Data["Title"] = ctx.Tr("admin.users.edit_account")
	ctx.Data["PageIsAdmin"] = true
	ctx.Data["PageIsAdminUsers"] = true

	uid := com.StrTo(ctx.Params(":userid")).MustInt64()
	if uid == 0 {
		ctx.Handle(404, "EditUser", nil)
		return
	}

	u, err := models.GetUserById(uid)
	if err != nil {
		ctx.Handle(500, "GetUserById", err)
		return
	}

	if ctx.HasError() {
		ctx.HTML(200, USER_EDIT)
		return
	}

	// NOTE: need password length check?
	if len(form.Passwd) > 0 {
		u.Passwd = form.Passwd
		u.Salt = models.GetUserSalt()
		u.EncodePasswd()
	}

	u.Email = form.Email
	u.Website = form.Website
	u.Location = form.Location
	if len(form.Avatar) == 0 {
		form.Avatar = form.Email
	}
	u.Avatar = base.EncodeMd5(form.Avatar)
	u.AvatarEmail = form.Avatar
	u.IsActive = form.Active
	u.IsAdmin = form.Admin
	if err := models.UpdateUser(u); err != nil {
		ctx.Handle(500, "UpdateUser", err)
		return
	}
	log.Trace("Account profile updated by admin(%s): %s", ctx.User.Name, u.Name)

	ctx.Data["User"] = u
	ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success"))
	ctx.Redirect("/admin/users/" + ctx.Params(":userid"))
}
Example #18
0
func SettingsPost(ctx *middleware.Context, form auth.UpdateProfileForm) {
	ctx.Data["Title"] = ctx.Tr("settings")
	ctx.Data["PageIsUserSettings"] = true
	ctx.Data["PageIsSettingsProfile"] = true

	if ctx.HasError() {
		ctx.HTML(200, SETTINGS_PROFILE)
		return
	}

	// Check if user name has been changed.
	if ctx.User.Name != form.UserName {
		isExist, err := models.IsUserExist(form.UserName)
		if err != nil {
			ctx.Handle(500, "IsUserExist", err)
			return
		} else if isExist {
			ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_PROFILE, &form)
			return
		} else if err = models.ChangeUserName(ctx.User, form.UserName); err != nil {
			if err == models.ErrUserNameIllegal {
				ctx.Flash.Error(ctx.Tr("form.illegal_username"))
				ctx.Redirect("/user/settings")
				return
			} else {
				ctx.Handle(500, "ChangeUserName", err)
			}
			return
		}
		log.Trace("User name changed: %s -> %s", ctx.User.Name, form.UserName)
		ctx.User.Name = form.UserName
	}

	ctx.User.FullName = form.FullName
	ctx.User.Email = form.Email
	ctx.User.Website = form.Website
	ctx.User.Location = form.Location
	ctx.User.Avatar = base.EncodeMd5(form.Avatar)
	ctx.User.AvatarEmail = form.Avatar
	if err := models.UpdateUser(ctx.User); err != nil {
		ctx.Handle(500, "UpdateUser", err)
		return
	}
	log.Trace("User setting updated: %s", ctx.User.Name)
	ctx.Flash.Success(ctx.Tr("settings.update_profile_success"))
	ctx.Redirect("/user/settings")
}
Example #19
0
func ResetPasswdPost(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("auth.reset_password")

	code := ctx.Query("code")
	if len(code) == 0 {
		ctx.Error(404)
		return
	}
	ctx.Data["Code"] = code

	if u := models.VerifyUserActiveCode(code); u != nil {
		// Validate password length.
		passwd := ctx.Query("password")
		if len(passwd) < 6 {
			ctx.Data["IsResetForm"] = true
			ctx.Data["Err_Password"] = true
			ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
			return
		}

		u.Passwd = passwd
		u.Rands = models.GetUserSalt()
		u.Salt = models.GetUserSalt()
		u.EncodePasswd()
		if err := models.UpdateUser(u); err != nil {
			ctx.Handle(500, "UpdateUser", err)
			return
		}

		log.Trace("User password reset: %s", u.Name)
		ctx.Redirect("/user/login")
		return
	}

	ctx.Data["IsResetFailed"] = true
	ctx.HTML(200, RESET_PASSWORD)
}
Example #20
0
func SocialSignIn(ctx *middleware.Context) {
	if setting.OauthService == nil {
		ctx.Handle(404, "social.SocialSignIn(oauth service not enabled)", nil)
		return
	}

	next := extractPath(ctx.Query("next"))
	name := ctx.Params(":name")
	connect, ok := social.SocialMap[name]
	if !ok {
		ctx.Handle(404, "social.SocialSignIn(social login not enabled)", errors.New(name))
		return
	}
	appUrl := strings.TrimSuffix(setting.AppUrl, "/")
	if name == "weibo" {
		appUrl = strings.Replace(appUrl, "localhost", "127.0.0.1", 1)
	}

	code := ctx.Query("code")
	if code == "" {
		// redirect to social login page
		connect.SetRedirectUrl(appUrl + ctx.Req.URL.Path)
		ctx.Redirect(connect.AuthCodeURL(next))
		return
	}

	// handle call back
	tk, err := connect.Exchange(code)
	if err != nil {
		ctx.Handle(500, "social.SocialSignIn(Exchange)", err)
		return
	}
	next = extractPath(ctx.Query("state"))
	log.Trace("social.SocialSignIn(Got token)")

	ui, err := connect.UserInfo(tk, ctx.Req.URL)
	if err != nil {
		ctx.Handle(500, fmt.Sprintf("social.SocialSignIn(get info from %s)", name), err)
		return
	}
	log.Info("social.SocialSignIn(social login): %s", ui)

	oa, err := models.GetOauth2(ui.Identity)
	switch err {
	case nil:
		ctx.Session.Set("uid", oa.User.Id)
		ctx.Session.Set("uname", oa.User.Name)
	case models.ErrOauth2RecordNotExist:
		raw, _ := json.Marshal(tk)
		oa = &models.Oauth2{
			Uid:      -1,
			Type:     connect.Type(),
			Identity: ui.Identity,
			Token:    string(raw),
		}
		log.Trace("social.SocialSignIn(oa): %v", oa)
		if err = models.AddOauth2(oa); err != nil {
			log.Error(4, "social.SocialSignIn(add oauth2): %v", err) // 501
			return
		}
	case models.ErrOauth2NotAssociated:
		next = "/user/sign_up"
	default:
		ctx.Handle(500, "social.SocialSignIn(GetOauth2)", err)
		return
	}

	oa.Updated = time.Now()
	if err = models.UpdateOauth2(oa); err != nil {
		log.Error(4, "UpdateOauth2: %v", err)
	}

	ctx.Session.Set("socialId", oa.Id)
	ctx.Session.Set("socialName", ui.Name)
	ctx.Session.Set("socialEmail", ui.Email)
	log.Trace("social.SocialSignIn(social ID): %v", oa.Id)
	ctx.Redirect(next)
}
Example #21
0
func InstallPost(ctx *middleware.Context, form auth.InstallForm) {
	if setting.InstallLock {
		ctx.Handle(404, "InstallPost", errors.New("Installation is prohibited"))
		return
	}

	ctx.Data["Title"] = ctx.Tr("install.install")
	ctx.Data["PageIsInstall"] = true

	renderDbOption(ctx)
	ctx.Data["CurDbOption"] = form.Database

	if ctx.HasError() {
		ctx.HTML(200, INSTALL)
		return
	}

	if _, err := exec.LookPath("git"); err != nil {
		ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), INSTALL, &form)
		return
	}

	// Pass basic check, now test configuration.
	// Test database setting.
	dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "SQLite3": "sqlite3"}
	models.DbCfg.Type = dbTypes[form.Database]
	models.DbCfg.Host = form.DbHost
	models.DbCfg.User = form.DbUser
	models.DbCfg.Pwd = form.DbPasswd
	models.DbCfg.Name = form.DatabaseName
	models.DbCfg.SslMode = form.SslMode
	models.DbCfg.Path = form.DatabasePath

	//	// Set test engine.
	//	var x *xorm.Engine
	//	if err := models.NewTestEngine(x); err != nil {
	//		// NOTE: should use core.QueryDriver (github.com/go-xorm/core)
	//		if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
	//			ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available"), INSTALL, &form)
	//		} else {
	//			ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &form)
	//		}
	//		return
	//	}

	// Test repository root path.
	if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
		ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &form)
		return
	}

	// Check run user.
	curUser := os.Getenv("USER")
	if len(curUser) == 0 {
		curUser = os.Getenv("USERNAME")
	}
	// Does not check run user when the install lock is off.
	if form.RunUser != curUser {
		ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, curUser), INSTALL, &form)
		return
	}

	// Check admin password.
	if form.AdminPasswd != form.ConfirmPasswd {
		ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, form)
		return
	}

	// Save settings.
	setting.Cfg.SetValue("database", "DB_TYPE", models.DbCfg.Type)
	setting.Cfg.SetValue("database", "HOST", models.DbCfg.Host)
	setting.Cfg.SetValue("database", "NAME", models.DbCfg.Name)
	setting.Cfg.SetValue("database", "USER", models.DbCfg.User)
	setting.Cfg.SetValue("database", "PASSWD", models.DbCfg.Pwd)
	setting.Cfg.SetValue("database", "SSL_MODE", models.DbCfg.SslMode)
	setting.Cfg.SetValue("database", "LOG_MODE", models.DbCfg.LogMode)
	setting.Cfg.SetValue("database", "PATH", models.DbCfg.Path)

	setting.Cfg.SetValue("repository", "ROOT", form.RepoRootPath)
	setting.Cfg.SetValue("", "RUN_USER", form.RunUser)
	setting.Cfg.SetValue("server", "DOMAIN", form.Domain)
	setting.Cfg.SetValue("server", "ROOT_URL", form.AppUrl)

	if len(strings.TrimSpace(form.SmtpHost)) > 0 {
		setting.Cfg.SetValue("mailer", "ENABLED", "true")
		setting.Cfg.SetValue("mailer", "HOST", form.SmtpHost)
		setting.Cfg.SetValue("mailer", "USER", form.SmtpEmail)
		setting.Cfg.SetValue("mailer", "PASSWD", form.SmtpPasswd)

		setting.Cfg.SetValue("service", "REGISTER_EMAIL_CONFIRM", com.ToStr(form.RegisterConfirm == "on"))
		setting.Cfg.SetValue("service", "ENABLE_NOTIFY_MAIL", com.ToStr(form.MailNotify == "on"))
	}

	setting.Cfg.SetValue("", "RUN_MODE", "prod")

	setting.Cfg.SetValue("log", "MODE", "file")

	setting.Cfg.SetValue("security", "INSTALL_LOCK", "true")

	os.MkdirAll("custom/conf", os.ModePerm)
	if err := goconfig.SaveConfigFile(setting.Cfg, path.Join(setting.CustomPath, "conf/app.ini")); err != nil {
		ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form)
		return
	}

	GlobalInit()

	// Create admin account.
	if err := models.CreateUser(&models.User{UserName: form.AdminName, Email: form.AdminEmail, Password: form.AdminPasswd,
		IsAdmin: true, IsActive: true}); err != nil {
		if err != models.ErrUserAlreadyExist {
			setting.InstallLock = false
			ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), INSTALL, &form)
			return
		}
		log.Info("Admin account already exist")
	}

	log.Info("First-time run install finished!")
	ctx.Flash.Success(ctx.Tr("install.install_success"))
	ctx.Redirect("/user/login")
}
Example #22
0
func SettingsSSHKeysPost(ctx *middleware.Context, form auth.AddSSHKeyForm) {
	ctx.Data["Title"] = ctx.Tr("settings")
	ctx.Data["PageIsUserSettings"] = true
	ctx.Data["PageIsSettingsSSHKeys"] = true

	var err error
	ctx.Data["Keys"], err = models.ListPublicKey(ctx.User.Id)
	if err != nil {
		ctx.Handle(500, "ssh.ListPublicKey", err)
		return
	}

	// Delete SSH key.
	if ctx.Query("_method") == "DELETE" {
		id := com.StrTo(ctx.Query("id")).MustInt64()
		if id <= 0 {
			return
		}

		if err = models.DeletePublicKey(&models.PublicKey{Id: id}); err != nil {
			ctx.Handle(500, "DeletePublicKey", err)
		} else {
			log.Trace("SSH key deleted: %s", ctx.User.Name)
			ctx.Redirect("/user/settings/ssh")
		}
		return
	}

	// Add new SSH key.
	if ctx.Req.Method == "POST" {
		if ctx.HasError() {
			ctx.HTML(200, SETTINGS_SSH_KEYS)
			return
		}

		// Remove newline characters from form.KeyContent
		cleanContent := strings.Replace(form.Content, "\n", "", -1)

		if ok, err := models.CheckPublicKeyString(cleanContent); !ok {
			ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
			ctx.Redirect("/user/settings/ssh")
			return
		}

		k := &models.PublicKey{
			OwnerId: ctx.User.Id,
			Name:    form.SSHTitle,
			Content: cleanContent,
		}
		if err := models.AddPublicKey(k); err != nil {
			if err == models.ErrKeyAlreadyExist {
				ctx.RenderWithErr(ctx.Tr("form.ssh_key_been_used"), SETTINGS_SSH_KEYS, &form)
				return
			}
			ctx.Handle(500, "ssh.AddPublicKey", err)
			return
		} else {
			log.Trace("SSH key added: %s", ctx.User.Name)
			ctx.Flash.Success(ctx.Tr("settings.add_key_success"))
			ctx.Redirect("/user/settings/ssh")
			return
		}
	}

	ctx.HTML(200, SETTINGS_SSH_KEYS)
}
Example #23
0
func SignUpPost(ctx *middleware.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
	ctx.Data["Title"] = ctx.Tr("sign_up")

	if setting.Service.DisableRegistration {
		ctx.Error(403)
		return
	}

	isOauth := false
	sid, isOauth := ctx.Session.Get("socialId").(int64)
	if isOauth {
		ctx.Data["IsSocialLogin"] = true
	}

	// May redirect from home page.
	if ctx.Query("from") == "home" {
		// Clear input error box.
		ctx.Data["Err_UserName"] = false
		ctx.Data["Err_Email"] = false

		// Make the best guess.
		uname := ctx.Query("uname")
		i := strings.Index(uname, "@")
		if i > -1 {
			ctx.Data["email"] = uname
			ctx.Data["uname"] = uname[:i]
		} else {
			ctx.Data["uname"] = uname
		}
		ctx.Data["password"] = ctx.Query("password")
		ctx.HTML(200, SIGNUP)
		return
	}

	if ctx.HasError() {
		ctx.HTML(200, SIGNUP)
		return
	}

	if !cpt.VerifyReq(ctx.Req) {
		ctx.Data["Err_Captcha"] = true
		ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &form)
		return
	} else if form.Password != form.Retype {
		ctx.Data["Err_Password"] = true
		ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &form)
		return
	}

	u := &models.User{
		Name:     form.UserName,
		Email:    form.Email,
		Passwd:   form.Password,
		IsActive: !setting.Service.RegisterEmailConfirm || isOauth,
	}

	if err := models.CreateUser(u); err != nil {
		switch err {
		case models.ErrUserAlreadyExist:
			ctx.Data["Err_UserName"] = true
			ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SIGNUP, &form)
		case models.ErrEmailAlreadyUsed:
			ctx.Data["Err_Email"] = true
			ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &form)
		case models.ErrUserNameIllegal:
			ctx.Data["Err_UserName"] = true
			ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SIGNUP, &form)
		default:
			ctx.Handle(500, "CreateUser", err)
		}
		return
	}
	log.Trace("Account created: %s", u.Name)

	// Bind social account.
	if isOauth {
		if err := models.BindUserOauth2(u.Id, sid); err != nil {
			ctx.Handle(500, "BindUserOauth2", err)
			return
		}
		ctx.Session.Delete("socialId")
		log.Trace("%s OAuth binded: %s -> %d", ctx.Req.RequestURI, form.UserName, sid)
	}

	// Send confirmation e-mail, no need for social account.
	if !isOauth && setting.Service.RegisterEmailConfirm && u.Id > 1 {
		mailer.SendRegisterMail(ctx.Render, u)
		ctx.Data["IsSendRegisterMail"] = true
		ctx.Data["Email"] = u.Email
		ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
		ctx.HTML(200, "user/activate")

		if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
			log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
		}
		return
	}

	ctx.Redirect("/user/login")
}