You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 39 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
10 years ago
10 years ago
9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
11 years ago
9 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/md5"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. "image"
  15. // Needed for jpeg support
  16. _ "image/jpeg"
  17. "image/png"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "time"
  22. "unicode/utf8"
  23. "github.com/Unknwon/com"
  24. "github.com/go-xorm/builder"
  25. "github.com/go-xorm/xorm"
  26. "github.com/nfnt/resize"
  27. "golang.org/x/crypto/pbkdf2"
  28. "code.gitea.io/git"
  29. api "code.gitea.io/sdk/gitea"
  30. "code.gitea.io/gitea/modules/avatar"
  31. "code.gitea.io/gitea/modules/base"
  32. "code.gitea.io/gitea/modules/log"
  33. "code.gitea.io/gitea/modules/markdown"
  34. "code.gitea.io/gitea/modules/setting"
  35. )
  36. // UserType defines the user type
  37. type UserType int
  38. const (
  39. // UserTypeIndividual defines an individual user
  40. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  41. // UserTypeOrganization defines an organization
  42. UserTypeOrganization
  43. )
  44. const syncExternalUsers = "sync_external_users"
  45. var (
  46. // ErrUserNotKeyOwner user does not own this key error
  47. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  48. // ErrEmailNotExist e-mail does not exist error
  49. ErrEmailNotExist = errors.New("E-mail does not exist")
  50. // ErrEmailNotActivated e-mail address has not been activated error
  51. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  52. // ErrUserNameIllegal user name contains illegal characters error
  53. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  54. // ErrLoginSourceNotActived login source is not actived error
  55. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  56. // ErrUnsupportedLoginType login source is unknown error
  57. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  58. )
  59. // User represents the object of individual and member of organization.
  60. type User struct {
  61. ID int64 `xorm:"pk autoincr"`
  62. LowerName string `xorm:"UNIQUE NOT NULL"`
  63. Name string `xorm:"UNIQUE NOT NULL"`
  64. FullName string
  65. // Email is the primary email address (to be used for communication)
  66. Email string `xorm:"NOT NULL"`
  67. KeepEmailPrivate bool
  68. Passwd string `xorm:"NOT NULL"`
  69. LoginType LoginType
  70. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  71. LoginName string
  72. Type UserType
  73. OwnedOrgs []*User `xorm:"-"`
  74. Orgs []*User `xorm:"-"`
  75. Repos []*Repository `xorm:"-"`
  76. Location string
  77. Website string
  78. Rands string `xorm:"VARCHAR(10)"`
  79. Salt string `xorm:"VARCHAR(10)"`
  80. Created time.Time `xorm:"-"`
  81. CreatedUnix int64 `xorm:"INDEX"`
  82. Updated time.Time `xorm:"-"`
  83. UpdatedUnix int64 `xorm:"INDEX"`
  84. LastLogin time.Time `xorm:"-"`
  85. LastLoginUnix int64 `xorm:"INDEX"`
  86. // Remember visibility choice for convenience, true for private
  87. LastRepoVisibility bool
  88. // Maximum repository creation limit, -1 means use global default
  89. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  90. // Permissions
  91. IsActive bool `xorm:"INDEX"` // Activate primary email
  92. IsAdmin bool
  93. AllowGitHook bool
  94. AllowImportLocal bool // Allow migrate repository by local path
  95. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  96. ProhibitLogin bool
  97. // Avatar
  98. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  99. AvatarEmail string `xorm:"NOT NULL"`
  100. UseCustomAvatar bool
  101. // Counters
  102. NumFollowers int
  103. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  104. NumStars int
  105. NumRepos int
  106. // For organization
  107. Description string
  108. NumTeams int
  109. NumMembers int
  110. Teams []*Team `xorm:"-"`
  111. Members []*User `xorm:"-"`
  112. // Preferences
  113. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  114. }
  115. // BeforeInsert is invoked from XORM before inserting an object of this type.
  116. func (u *User) BeforeInsert() {
  117. u.CreatedUnix = time.Now().Unix()
  118. u.UpdatedUnix = u.CreatedUnix
  119. }
  120. // BeforeUpdate is invoked from XORM before updating this object.
  121. func (u *User) BeforeUpdate() {
  122. if u.MaxRepoCreation < -1 {
  123. u.MaxRepoCreation = -1
  124. }
  125. u.UpdatedUnix = time.Now().Unix()
  126. }
  127. // SetLastLogin set time to last login
  128. func (u *User) SetLastLogin() {
  129. u.LastLoginUnix = time.Now().Unix()
  130. }
  131. // UpdateDiffViewStyle updates the users diff view style
  132. func (u *User) UpdateDiffViewStyle(style string) error {
  133. u.DiffViewStyle = style
  134. return UpdateUser(u)
  135. }
  136. // AfterSet is invoked from XORM after setting the value of a field of this object.
  137. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  138. switch colName {
  139. case "full_name":
  140. u.FullName = markdown.Sanitize(u.FullName)
  141. case "created_unix":
  142. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  143. case "updated_unix":
  144. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  145. case "last_login_unix":
  146. u.LastLogin = time.Unix(u.LastLoginUnix, 0).Local()
  147. }
  148. }
  149. // getEmail returns an noreply email, if the user has set to keep his
  150. // email address private, otherwise the primary email address.
  151. func (u *User) getEmail() string {
  152. if u.KeepEmailPrivate {
  153. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  154. }
  155. return u.Email
  156. }
  157. // APIFormat converts a User to api.User
  158. func (u *User) APIFormat() *api.User {
  159. return &api.User{
  160. ID: u.ID,
  161. UserName: u.Name,
  162. FullName: u.FullName,
  163. Email: u.getEmail(),
  164. AvatarURL: u.AvatarLink(),
  165. }
  166. }
  167. // IsLocal returns true if user login type is LoginPlain.
  168. func (u *User) IsLocal() bool {
  169. return u.LoginType <= LoginPlain
  170. }
  171. // IsOAuth2 returns true if user login type is LoginOAuth2.
  172. func (u *User) IsOAuth2() bool {
  173. return u.LoginType == LoginOAuth2
  174. }
  175. // HasForkedRepo checks if user has already forked a repository with given ID.
  176. func (u *User) HasForkedRepo(repoID int64) bool {
  177. _, has := HasForkedRepo(u.ID, repoID)
  178. return has
  179. }
  180. // RepoCreationNum returns the number of repositories created by the user
  181. func (u *User) RepoCreationNum() int {
  182. if u.MaxRepoCreation <= -1 {
  183. return setting.Repository.MaxCreationLimit
  184. }
  185. return u.MaxRepoCreation
  186. }
  187. // CanCreateRepo returns if user login can create a repository
  188. func (u *User) CanCreateRepo() bool {
  189. if u.MaxRepoCreation <= -1 {
  190. if setting.Repository.MaxCreationLimit <= -1 {
  191. return true
  192. }
  193. return u.NumRepos < setting.Repository.MaxCreationLimit
  194. }
  195. return u.NumRepos < u.MaxRepoCreation
  196. }
  197. // CanCreateOrganization returns true if user can create organisation.
  198. func (u *User) CanCreateOrganization() bool {
  199. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  200. }
  201. // CanEditGitHook returns true if user can edit Git hooks.
  202. func (u *User) CanEditGitHook() bool {
  203. return u.IsAdmin || u.AllowGitHook
  204. }
  205. // CanImportLocal returns true if user can migrate repository by local path.
  206. func (u *User) CanImportLocal() bool {
  207. if !setting.ImportLocalPaths {
  208. return false
  209. }
  210. return u.IsAdmin || u.AllowImportLocal
  211. }
  212. // DashboardLink returns the user dashboard page link.
  213. func (u *User) DashboardLink() string {
  214. if u.IsOrganization() {
  215. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  216. }
  217. return setting.AppSubURL + "/"
  218. }
  219. // HomeLink returns the user or organization home page link.
  220. func (u *User) HomeLink() string {
  221. return setting.AppSubURL + "/" + u.Name
  222. }
  223. // HTMLURL returns the user or organization's full link.
  224. func (u *User) HTMLURL() string {
  225. return setting.AppURL + u.Name
  226. }
  227. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  228. func (u *User) GenerateEmailActivateCode(email string) string {
  229. code := base.CreateTimeLimitCode(
  230. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  231. setting.Service.ActiveCodeLives, nil)
  232. // Add tail hex username
  233. code += hex.EncodeToString([]byte(u.LowerName))
  234. return code
  235. }
  236. // GenerateActivateCode generates an activate code based on user information.
  237. func (u *User) GenerateActivateCode() string {
  238. return u.GenerateEmailActivateCode(u.Email)
  239. }
  240. // CustomAvatarPath returns user custom avatar file path.
  241. func (u *User) CustomAvatarPath() string {
  242. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  243. }
  244. // GenerateRandomAvatar generates a random avatar for user.
  245. func (u *User) GenerateRandomAvatar() error {
  246. return u.generateRandomAvatar(x)
  247. }
  248. func (u *User) generateRandomAvatar(e Engine) error {
  249. seed := u.Email
  250. if len(seed) == 0 {
  251. seed = u.Name
  252. }
  253. img, err := avatar.RandomImage([]byte(seed))
  254. if err != nil {
  255. return fmt.Errorf("RandomImage: %v", err)
  256. }
  257. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  258. // since random image is not a user's photo, there is no security for enumable
  259. u.Avatar = fmt.Sprintf("%d", u.ID)
  260. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  261. return fmt.Errorf("MkdirAll: %v", err)
  262. }
  263. fw, err := os.Create(u.CustomAvatarPath())
  264. if err != nil {
  265. return fmt.Errorf("Create: %v", err)
  266. }
  267. defer fw.Close()
  268. if _, err := e.Id(u.ID).Cols("avatar").Update(u); err != nil {
  269. return err
  270. }
  271. if err = png.Encode(fw, img); err != nil {
  272. return fmt.Errorf("Encode: %v", err)
  273. }
  274. log.Info("New random avatar created: %d", u.ID)
  275. return nil
  276. }
  277. // RelAvatarLink returns relative avatar link to the site domain,
  278. // which includes app sub-url as prefix. However, it is possible
  279. // to return full URL if user enables Gravatar-like service.
  280. func (u *User) RelAvatarLink() string {
  281. defaultImgURL := setting.AppSubURL + "/img/avatar_default.png"
  282. if u.ID == -1 {
  283. return defaultImgURL
  284. }
  285. switch {
  286. case u.UseCustomAvatar:
  287. if !com.IsFile(u.CustomAvatarPath()) {
  288. return defaultImgURL
  289. }
  290. return setting.AppSubURL + "/avatars/" + u.Avatar
  291. case setting.DisableGravatar, setting.OfflineMode:
  292. if !com.IsFile(u.CustomAvatarPath()) {
  293. if err := u.GenerateRandomAvatar(); err != nil {
  294. log.Error(3, "GenerateRandomAvatar: %v", err)
  295. }
  296. }
  297. return setting.AppSubURL + "/avatars/" + u.Avatar
  298. }
  299. return base.AvatarLink(u.AvatarEmail)
  300. }
  301. // AvatarLink returns user avatar absolute link.
  302. func (u *User) AvatarLink() string {
  303. link := u.RelAvatarLink()
  304. if link[0] == '/' && link[1] != '/' {
  305. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  306. }
  307. return link
  308. }
  309. // GetFollowers returns range of user's followers.
  310. func (u *User) GetFollowers(page int) ([]*User, error) {
  311. users := make([]*User, 0, ItemsPerPage)
  312. sess := x.
  313. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  314. Where("follow.follow_id=?", u.ID)
  315. if setting.UsePostgreSQL {
  316. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  317. } else {
  318. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  319. }
  320. return users, sess.Find(&users)
  321. }
  322. // IsFollowing returns true if user is following followID.
  323. func (u *User) IsFollowing(followID int64) bool {
  324. return IsFollowing(u.ID, followID)
  325. }
  326. // GetFollowing returns range of user's following.
  327. func (u *User) GetFollowing(page int) ([]*User, error) {
  328. users := make([]*User, 0, ItemsPerPage)
  329. sess := x.
  330. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  331. Where("follow.user_id=?", u.ID)
  332. if setting.UsePostgreSQL {
  333. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  334. } else {
  335. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  336. }
  337. return users, sess.Find(&users)
  338. }
  339. // NewGitSig generates and returns the signature of given user.
  340. func (u *User) NewGitSig() *git.Signature {
  341. return &git.Signature{
  342. Name: u.DisplayName(),
  343. Email: u.getEmail(),
  344. When: time.Now(),
  345. }
  346. }
  347. // EncodePasswd encodes password to safe format.
  348. func (u *User) EncodePasswd() {
  349. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  350. u.Passwd = fmt.Sprintf("%x", newPasswd)
  351. }
  352. // ValidatePassword checks if given password matches the one belongs to the user.
  353. func (u *User) ValidatePassword(passwd string) bool {
  354. newUser := &User{Passwd: passwd, Salt: u.Salt}
  355. newUser.EncodePasswd()
  356. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  357. }
  358. // IsPasswordSet checks if the password is set or left empty
  359. func (u *User) IsPasswordSet() bool {
  360. return !u.ValidatePassword("")
  361. }
  362. // UploadAvatar saves custom avatar for user.
  363. // FIXME: split uploads to different subdirs in case we have massive users.
  364. func (u *User) UploadAvatar(data []byte) error {
  365. img, _, err := image.Decode(bytes.NewReader(data))
  366. if err != nil {
  367. return fmt.Errorf("Decode: %v", err)
  368. }
  369. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  370. sess := x.NewSession()
  371. defer sessionRelease(sess)
  372. if err = sess.Begin(); err != nil {
  373. return err
  374. }
  375. u.UseCustomAvatar = true
  376. u.Avatar = fmt.Sprintf("%x", md5.Sum(data))
  377. if err = updateUser(sess, u); err != nil {
  378. return fmt.Errorf("updateUser: %v", err)
  379. }
  380. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  381. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  382. }
  383. fw, err := os.Create(u.CustomAvatarPath())
  384. if err != nil {
  385. return fmt.Errorf("Create: %v", err)
  386. }
  387. defer fw.Close()
  388. if err = png.Encode(fw, m); err != nil {
  389. return fmt.Errorf("Encode: %v", err)
  390. }
  391. return sess.Commit()
  392. }
  393. // DeleteAvatar deletes the user's custom avatar.
  394. func (u *User) DeleteAvatar() error {
  395. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  396. if len(u.Avatar) > 0 {
  397. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  398. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  399. }
  400. }
  401. u.UseCustomAvatar = false
  402. u.Avatar = ""
  403. if _, err := x.Id(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  404. return fmt.Errorf("UpdateUser: %v", err)
  405. }
  406. return nil
  407. }
  408. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  409. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  410. has, err := HasAccess(u.ID, repo, AccessModeAdmin)
  411. if err != nil {
  412. log.Error(3, "HasAccess: %v", err)
  413. }
  414. return has
  415. }
  416. // IsWriterOfRepo returns true if user has write access to given repository.
  417. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  418. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  419. if err != nil {
  420. log.Error(3, "HasAccess: %v", err)
  421. }
  422. return has
  423. }
  424. // IsOrganization returns true if user is actually a organization.
  425. func (u *User) IsOrganization() bool {
  426. return u.Type == UserTypeOrganization
  427. }
  428. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  429. func (u *User) IsUserOrgOwner(orgID int64) bool {
  430. return IsOrganizationOwner(orgID, u.ID)
  431. }
  432. // IsPublicMember returns true if user public his/her membership in given organization.
  433. func (u *User) IsPublicMember(orgID int64) bool {
  434. return IsPublicMembership(orgID, u.ID)
  435. }
  436. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  437. return e.
  438. Where("uid=?", u.ID).
  439. Count(new(OrgUser))
  440. }
  441. // GetOrganizationCount returns count of membership of organization of user.
  442. func (u *User) GetOrganizationCount() (int64, error) {
  443. return u.getOrganizationCount(x)
  444. }
  445. // GetRepositories returns repositories that user owns, including private repositories.
  446. func (u *User) GetRepositories(page, pageSize int) (err error) {
  447. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  448. return err
  449. }
  450. // GetRepositoryIDs returns repositories IDs where user owned
  451. func (u *User) GetRepositoryIDs() ([]int64, error) {
  452. var ids []int64
  453. return ids, x.Table("repository").Cols("id").Where("owner_id = ?", u.ID).Find(&ids)
  454. }
  455. // GetOrgRepositoryIDs returns repositories IDs where user's team owned
  456. func (u *User) GetOrgRepositoryIDs() ([]int64, error) {
  457. var ids []int64
  458. return ids, x.Table("repository").
  459. Cols("repository.id").
  460. Join("INNER", "team_user", "repository.owner_id = team_user.org_id AND team_user.uid = ?", u.ID).
  461. GroupBy("repository.id").Find(&ids)
  462. }
  463. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  464. func (u *User) GetAccessRepoIDs() ([]int64, error) {
  465. ids, err := u.GetRepositoryIDs()
  466. if err != nil {
  467. return nil, err
  468. }
  469. ids2, err := u.GetOrgRepositoryIDs()
  470. if err != nil {
  471. return nil, err
  472. }
  473. return append(ids, ids2...), nil
  474. }
  475. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  476. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  477. return GetUserMirrorRepositories(u.ID)
  478. }
  479. // GetOwnedOrganizations returns all organizations that user owns.
  480. func (u *User) GetOwnedOrganizations() (err error) {
  481. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  482. return err
  483. }
  484. // GetOrganizations returns all organizations that user belongs to.
  485. func (u *User) GetOrganizations(all bool) error {
  486. ous, err := GetOrgUsersByUserID(u.ID, all)
  487. if err != nil {
  488. return err
  489. }
  490. u.Orgs = make([]*User, len(ous))
  491. for i, ou := range ous {
  492. u.Orgs[i], err = GetUserByID(ou.OrgID)
  493. if err != nil {
  494. return err
  495. }
  496. }
  497. return nil
  498. }
  499. // DisplayName returns full name if it's not empty,
  500. // returns username otherwise.
  501. func (u *User) DisplayName() string {
  502. if len(u.FullName) > 0 {
  503. return u.FullName
  504. }
  505. return u.Name
  506. }
  507. // ShortName ellipses username to length
  508. func (u *User) ShortName(length int) string {
  509. return base.EllipsisString(u.Name, length)
  510. }
  511. // IsMailable checks if a user is eligible
  512. // to receive emails.
  513. func (u *User) IsMailable() bool {
  514. return u.IsActive
  515. }
  516. // IsUserExist checks if given user name exist,
  517. // the user name should be noncased unique.
  518. // If uid is presented, then check will rule out that one,
  519. // it is used when update a user name in settings page.
  520. func IsUserExist(uid int64, name string) (bool, error) {
  521. if len(name) == 0 {
  522. return false, nil
  523. }
  524. return x.
  525. Where("id!=?", uid).
  526. Get(&User{LowerName: strings.ToLower(name)})
  527. }
  528. // GetUserSalt returns a random user salt token.
  529. func GetUserSalt() (string, error) {
  530. return base.GetRandomString(10)
  531. }
  532. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  533. func NewGhostUser() *User {
  534. return &User{
  535. ID: -1,
  536. Name: "Ghost",
  537. LowerName: "ghost",
  538. }
  539. }
  540. var (
  541. reservedUsernames = []string{"assets", "css", "explore", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  542. reservedUserPatterns = []string{"*.keys"}
  543. )
  544. // isUsableName checks if name is reserved or pattern of name is not allowed
  545. // based on given reserved names and patterns.
  546. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  547. func isUsableName(names, patterns []string, name string) error {
  548. name = strings.TrimSpace(strings.ToLower(name))
  549. if utf8.RuneCountInString(name) == 0 {
  550. return ErrNameEmpty
  551. }
  552. for i := range names {
  553. if name == names[i] {
  554. return ErrNameReserved{name}
  555. }
  556. }
  557. for _, pat := range patterns {
  558. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  559. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  560. return ErrNamePatternNotAllowed{pat}
  561. }
  562. }
  563. return nil
  564. }
  565. // IsUsableUsername returns an error when a username is reserved
  566. func IsUsableUsername(name string) error {
  567. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  568. }
  569. // CreateUser creates record of a new user.
  570. func CreateUser(u *User) (err error) {
  571. if err = IsUsableUsername(u.Name); err != nil {
  572. return err
  573. }
  574. isExist, err := IsUserExist(0, u.Name)
  575. if err != nil {
  576. return err
  577. } else if isExist {
  578. return ErrUserAlreadyExist{u.Name}
  579. }
  580. u.Email = strings.ToLower(u.Email)
  581. has, err := x.
  582. Where("email=?", u.Email).
  583. Get(new(User))
  584. if err != nil {
  585. return err
  586. } else if has {
  587. return ErrEmailAlreadyUsed{u.Email}
  588. }
  589. isExist, err = IsEmailUsed(u.Email)
  590. if err != nil {
  591. return err
  592. } else if isExist {
  593. return ErrEmailAlreadyUsed{u.Email}
  594. }
  595. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  596. u.LowerName = strings.ToLower(u.Name)
  597. u.AvatarEmail = u.Email
  598. u.Avatar = base.HashEmail(u.AvatarEmail)
  599. if u.Rands, err = GetUserSalt(); err != nil {
  600. return err
  601. }
  602. if u.Salt, err = GetUserSalt(); err != nil {
  603. return err
  604. }
  605. u.EncodePasswd()
  606. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  607. u.MaxRepoCreation = -1
  608. sess := x.NewSession()
  609. defer sessionRelease(sess)
  610. if err = sess.Begin(); err != nil {
  611. return err
  612. }
  613. if _, err = sess.Insert(u); err != nil {
  614. return err
  615. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  616. return err
  617. }
  618. return sess.Commit()
  619. }
  620. func countUsers(e Engine) int64 {
  621. count, _ := e.
  622. Where("type=0").
  623. Count(new(User))
  624. return count
  625. }
  626. // CountUsers returns number of users.
  627. func CountUsers() int64 {
  628. return countUsers(x)
  629. }
  630. // Users returns number of users in given page.
  631. func Users(opts *SearchUserOptions) ([]*User, error) {
  632. if len(opts.OrderBy) == 0 {
  633. opts.OrderBy = "name ASC"
  634. }
  635. users := make([]*User, 0, opts.PageSize)
  636. sess := x.
  637. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  638. Where("type=0")
  639. return users, sess.
  640. OrderBy(opts.OrderBy).
  641. Find(&users)
  642. }
  643. // get user by verify code
  644. func getVerifyUser(code string) (user *User) {
  645. if len(code) <= base.TimeLimitCodeLength {
  646. return nil
  647. }
  648. // use tail hex username query user
  649. hexStr := code[base.TimeLimitCodeLength:]
  650. if b, err := hex.DecodeString(hexStr); err == nil {
  651. if user, err = GetUserByName(string(b)); user != nil {
  652. return user
  653. }
  654. log.Error(4, "user.getVerifyUser: %v", err)
  655. }
  656. return nil
  657. }
  658. // VerifyUserActiveCode verifies active code when active account
  659. func VerifyUserActiveCode(code string) (user *User) {
  660. minutes := setting.Service.ActiveCodeLives
  661. if user = getVerifyUser(code); user != nil {
  662. // time limit code
  663. prefix := code[:base.TimeLimitCodeLength]
  664. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  665. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  666. return user
  667. }
  668. }
  669. return nil
  670. }
  671. // VerifyActiveEmailCode verifies active email code when active account
  672. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  673. minutes := setting.Service.ActiveCodeLives
  674. if user := getVerifyUser(code); user != nil {
  675. // time limit code
  676. prefix := code[:base.TimeLimitCodeLength]
  677. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  678. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  679. emailAddress := &EmailAddress{Email: email}
  680. if has, _ := x.Get(emailAddress); has {
  681. return emailAddress
  682. }
  683. }
  684. }
  685. return nil
  686. }
  687. // ChangeUserName changes all corresponding setting from old user name to new one.
  688. func ChangeUserName(u *User, newUserName string) (err error) {
  689. if err = IsUsableUsername(newUserName); err != nil {
  690. return err
  691. }
  692. isExist, err := IsUserExist(0, newUserName)
  693. if err != nil {
  694. return err
  695. } else if isExist {
  696. return ErrUserAlreadyExist{newUserName}
  697. }
  698. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  699. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  700. }
  701. // Delete all local copies of repository wiki that user owns.
  702. if err = x.
  703. Where("owner_id=?", u.ID).
  704. Iterate(new(Repository), func(idx int, bean interface{}) error {
  705. repo := bean.(*Repository)
  706. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  707. return nil
  708. }); err != nil {
  709. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  710. }
  711. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  712. }
  713. // checkDupEmail checks whether there are the same email with the user
  714. func checkDupEmail(e Engine, u *User) error {
  715. u.Email = strings.ToLower(u.Email)
  716. has, err := e.
  717. Where("id!=?", u.ID).
  718. And("type=?", u.Type).
  719. And("email=?", u.Email).
  720. Get(new(User))
  721. if err != nil {
  722. return err
  723. } else if has {
  724. return ErrEmailAlreadyUsed{u.Email}
  725. }
  726. return nil
  727. }
  728. func updateUser(e Engine, u *User) error {
  729. // Organization does not need email
  730. u.Email = strings.ToLower(u.Email)
  731. if !u.IsOrganization() {
  732. if len(u.AvatarEmail) == 0 {
  733. u.AvatarEmail = u.Email
  734. }
  735. u.Avatar = base.HashEmail(u.AvatarEmail)
  736. }
  737. u.LowerName = strings.ToLower(u.Name)
  738. u.Location = base.TruncateString(u.Location, 255)
  739. u.Website = base.TruncateString(u.Website, 255)
  740. u.Description = base.TruncateString(u.Description, 255)
  741. u.FullName = markdown.Sanitize(u.FullName)
  742. _, err := e.Id(u.ID).AllCols().Update(u)
  743. return err
  744. }
  745. // UpdateUser updates user's information.
  746. func UpdateUser(u *User) error {
  747. return updateUser(x, u)
  748. }
  749. // UpdateUserSetting updates user's settings.
  750. func UpdateUserSetting(u *User) error {
  751. if !u.IsOrganization() {
  752. if err := checkDupEmail(x, u); err != nil {
  753. return err
  754. }
  755. }
  756. return updateUser(x, u)
  757. }
  758. // deleteBeans deletes all given beans, beans should contain delete conditions.
  759. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  760. for i := range beans {
  761. if _, err = e.Delete(beans[i]); err != nil {
  762. return err
  763. }
  764. }
  765. return nil
  766. }
  767. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  768. func deleteUser(e *xorm.Session, u *User) error {
  769. // Note: A user owns any repository or belongs to any organization
  770. // cannot perform delete operation.
  771. // Check ownership of repository.
  772. count, err := getRepositoryCount(e, u)
  773. if err != nil {
  774. return fmt.Errorf("GetRepositoryCount: %v", err)
  775. } else if count > 0 {
  776. return ErrUserOwnRepos{UID: u.ID}
  777. }
  778. // Check membership of organization.
  779. count, err = u.getOrganizationCount(e)
  780. if err != nil {
  781. return fmt.Errorf("GetOrganizationCount: %v", err)
  782. } else if count > 0 {
  783. return ErrUserHasOrgs{UID: u.ID}
  784. }
  785. // ***** START: Watch *****
  786. watches := make([]*Watch, 0, 10)
  787. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  788. return fmt.Errorf("get all watches: %v", err)
  789. }
  790. for i := range watches {
  791. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  792. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  793. }
  794. }
  795. // ***** END: Watch *****
  796. // ***** START: Star *****
  797. stars := make([]*Star, 0, 10)
  798. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  799. return fmt.Errorf("get all stars: %v", err)
  800. }
  801. for i := range stars {
  802. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  803. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  804. }
  805. }
  806. // ***** END: Star *****
  807. // ***** START: Follow *****
  808. followers := make([]*Follow, 0, 10)
  809. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  810. return fmt.Errorf("get all followers: %v", err)
  811. }
  812. for i := range followers {
  813. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  814. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  815. }
  816. }
  817. // ***** END: Follow *****
  818. if err = deleteBeans(e,
  819. &AccessToken{UID: u.ID},
  820. &Collaboration{UserID: u.ID},
  821. &Access{UserID: u.ID},
  822. &Watch{UserID: u.ID},
  823. &Star{UID: u.ID},
  824. &Follow{FollowID: u.ID},
  825. &Action{UserID: u.ID},
  826. &IssueUser{UID: u.ID},
  827. &EmailAddress{UID: u.ID},
  828. &UserOpenID{UID: u.ID},
  829. ); err != nil {
  830. return fmt.Errorf("deleteBeans: %v", err)
  831. }
  832. // ***** START: PublicKey *****
  833. keys := make([]*PublicKey, 0, 10)
  834. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  835. return fmt.Errorf("get all public keys: %v", err)
  836. }
  837. keyIDs := make([]int64, len(keys))
  838. for i := range keys {
  839. keyIDs[i] = keys[i].ID
  840. }
  841. if err = deletePublicKeys(e, keyIDs...); err != nil {
  842. return fmt.Errorf("deletePublicKeys: %v", err)
  843. }
  844. // ***** END: PublicKey *****
  845. // Clear assignee.
  846. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  847. return fmt.Errorf("clear assignee: %v", err)
  848. }
  849. // ***** START: ExternalLoginUser *****
  850. if err = removeAllAccountLinks(e, u); err != nil {
  851. return fmt.Errorf("ExternalLoginUser: %v", err)
  852. }
  853. // ***** END: ExternalLoginUser *****
  854. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  855. return fmt.Errorf("Delete: %v", err)
  856. }
  857. // FIXME: system notice
  858. // Note: There are something just cannot be roll back,
  859. // so just keep error logs of those operations.
  860. path := UserPath(u.Name)
  861. if err := os.RemoveAll(path); err != nil {
  862. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  863. }
  864. if len(u.Avatar) > 0 {
  865. avatarPath := u.CustomAvatarPath()
  866. if com.IsExist(avatarPath) {
  867. if err := os.Remove(avatarPath); err != nil {
  868. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  869. }
  870. }
  871. }
  872. return nil
  873. }
  874. // DeleteUser completely and permanently deletes everything of a user,
  875. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  876. func DeleteUser(u *User) (err error) {
  877. sess := x.NewSession()
  878. defer sessionRelease(sess)
  879. if err = sess.Begin(); err != nil {
  880. return err
  881. }
  882. if err = deleteUser(sess, u); err != nil {
  883. // Note: don't wrapper error here.
  884. return err
  885. }
  886. if err = sess.Commit(); err != nil {
  887. return err
  888. }
  889. return RewriteAllPublicKeys()
  890. }
  891. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  892. func DeleteInactivateUsers() (err error) {
  893. users := make([]*User, 0, 10)
  894. if err = x.
  895. Where("is_active = ?", false).
  896. Find(&users); err != nil {
  897. return fmt.Errorf("get all inactive users: %v", err)
  898. }
  899. // FIXME: should only update authorized_keys file once after all deletions.
  900. for _, u := range users {
  901. if err = DeleteUser(u); err != nil {
  902. // Ignore users that were set inactive by admin.
  903. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  904. continue
  905. }
  906. return err
  907. }
  908. }
  909. _, err = x.
  910. Where("is_activated = ?", false).
  911. Delete(new(EmailAddress))
  912. return err
  913. }
  914. // UserPath returns the path absolute path of user repositories.
  915. func UserPath(userName string) string {
  916. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  917. }
  918. // GetUserByKeyID get user information by user's public key id
  919. func GetUserByKeyID(keyID int64) (*User, error) {
  920. var user User
  921. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  922. Where("`public_key`.id=?", keyID).
  923. Get(&user)
  924. if err != nil {
  925. return nil, err
  926. }
  927. if !has {
  928. return nil, ErrUserNotExist{0, "", keyID}
  929. }
  930. return &user, nil
  931. }
  932. func getUserByID(e Engine, id int64) (*User, error) {
  933. u := new(User)
  934. has, err := e.Id(id).Get(u)
  935. if err != nil {
  936. return nil, err
  937. } else if !has {
  938. return nil, ErrUserNotExist{id, "", 0}
  939. }
  940. return u, nil
  941. }
  942. // GetUserByID returns the user object by given ID if exists.
  943. func GetUserByID(id int64) (*User, error) {
  944. return getUserByID(x, id)
  945. }
  946. // GetAssigneeByID returns the user with write access of repository by given ID.
  947. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  948. has, err := HasAccess(userID, repo, AccessModeWrite)
  949. if err != nil {
  950. return nil, err
  951. } else if !has {
  952. return nil, ErrUserNotExist{userID, "", 0}
  953. }
  954. return GetUserByID(userID)
  955. }
  956. // GetUserByName returns user by given name.
  957. func GetUserByName(name string) (*User, error) {
  958. if len(name) == 0 {
  959. return nil, ErrUserNotExist{0, name, 0}
  960. }
  961. u := &User{LowerName: strings.ToLower(name)}
  962. has, err := x.Get(u)
  963. if err != nil {
  964. return nil, err
  965. } else if !has {
  966. return nil, ErrUserNotExist{0, name, 0}
  967. }
  968. return u, nil
  969. }
  970. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  971. func GetUserEmailsByNames(names []string) []string {
  972. mails := make([]string, 0, len(names))
  973. for _, name := range names {
  974. u, err := GetUserByName(name)
  975. if err != nil {
  976. continue
  977. }
  978. if u.IsMailable() {
  979. mails = append(mails, u.Email)
  980. }
  981. }
  982. return mails
  983. }
  984. // GetUsersByIDs returns all resolved users from a list of Ids.
  985. func GetUsersByIDs(ids []int64) ([]*User, error) {
  986. ous := make([]*User, 0, len(ids))
  987. if len(ids) == 0 {
  988. return ous, nil
  989. }
  990. err := x.In("id", ids).
  991. Asc("name").
  992. Find(&ous)
  993. return ous, err
  994. }
  995. // GetUserIDsByNames returns a slice of ids corresponds to names.
  996. func GetUserIDsByNames(names []string) []int64 {
  997. ids := make([]int64, 0, len(names))
  998. for _, name := range names {
  999. u, err := GetUserByName(name)
  1000. if err != nil {
  1001. continue
  1002. }
  1003. ids = append(ids, u.ID)
  1004. }
  1005. return ids
  1006. }
  1007. // UserCommit represents a commit with validation of user.
  1008. type UserCommit struct {
  1009. User *User
  1010. *git.Commit
  1011. }
  1012. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1013. func ValidateCommitWithEmail(c *git.Commit) *User {
  1014. u, err := GetUserByEmail(c.Author.Email)
  1015. if err != nil {
  1016. return nil
  1017. }
  1018. return u
  1019. }
  1020. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1021. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1022. var (
  1023. u *User
  1024. emails = map[string]*User{}
  1025. newCommits = list.New()
  1026. e = oldCommits.Front()
  1027. )
  1028. for e != nil {
  1029. c := e.Value.(*git.Commit)
  1030. if v, ok := emails[c.Author.Email]; !ok {
  1031. u, _ = GetUserByEmail(c.Author.Email)
  1032. emails[c.Author.Email] = u
  1033. } else {
  1034. u = v
  1035. }
  1036. newCommits.PushBack(UserCommit{
  1037. User: u,
  1038. Commit: c,
  1039. })
  1040. e = e.Next()
  1041. }
  1042. return newCommits
  1043. }
  1044. // GetUserByEmail returns the user object by given e-mail if exists.
  1045. func GetUserByEmail(email string) (*User, error) {
  1046. if len(email) == 0 {
  1047. return nil, ErrUserNotExist{0, email, 0}
  1048. }
  1049. email = strings.ToLower(email)
  1050. // First try to find the user by primary email
  1051. user := &User{Email: email}
  1052. has, err := x.Get(user)
  1053. if err != nil {
  1054. return nil, err
  1055. }
  1056. if has {
  1057. return user, nil
  1058. }
  1059. // Otherwise, check in alternative list for activated email addresses
  1060. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1061. has, err = x.Get(emailAddress)
  1062. if err != nil {
  1063. return nil, err
  1064. }
  1065. if has {
  1066. return GetUserByID(emailAddress.UID)
  1067. }
  1068. return nil, ErrUserNotExist{0, email, 0}
  1069. }
  1070. // GetUser checks if a user already exists
  1071. func GetUser(user *User) (bool, error) {
  1072. return x.Get(user)
  1073. }
  1074. // SearchUserOptions contains the options for searching
  1075. type SearchUserOptions struct {
  1076. Keyword string
  1077. Type UserType
  1078. OrderBy string
  1079. Page int
  1080. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1081. }
  1082. // SearchUserByName takes keyword and part of user name to search,
  1083. // it returns results in given range and number of total results.
  1084. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1085. if len(opts.Keyword) == 0 {
  1086. return users, 0, nil
  1087. }
  1088. opts.Keyword = strings.ToLower(opts.Keyword)
  1089. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1090. opts.PageSize = setting.UI.ExplorePagingNum
  1091. }
  1092. if opts.Page <= 0 {
  1093. opts.Page = 1
  1094. }
  1095. users = make([]*User, 0, opts.PageSize)
  1096. // Append conditions
  1097. cond := builder.And(
  1098. builder.Eq{"type": opts.Type},
  1099. builder.Or(
  1100. builder.Like{"lower_name", opts.Keyword},
  1101. builder.Like{"LOWER(full_name)", opts.Keyword},
  1102. ),
  1103. )
  1104. count, err := x.Where(cond).Count(new(User))
  1105. if err != nil {
  1106. return nil, 0, fmt.Errorf("Count: %v", err)
  1107. }
  1108. sess := x.Where(cond).
  1109. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1110. if len(opts.OrderBy) > 0 {
  1111. sess.OrderBy(opts.OrderBy)
  1112. }
  1113. return users, count, sess.Find(&users)
  1114. }
  1115. // GetStarredRepos returns the repos starred by a particular user
  1116. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1117. sess := x.Where("star.uid=?", userID).
  1118. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1119. if !private {
  1120. sess = sess.And("is_private=?", false)
  1121. }
  1122. repos := make([]*Repository, 0, 10)
  1123. err := sess.Find(&repos)
  1124. if err != nil {
  1125. return nil, err
  1126. }
  1127. return repos, nil
  1128. }
  1129. // GetWatchedRepos returns the repos watched by a particular user
  1130. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1131. sess := x.Where("watch.user_id=?", userID).
  1132. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1133. if !private {
  1134. sess = sess.And("is_private=?", false)
  1135. }
  1136. repos := make([]*Repository, 0, 10)
  1137. err := sess.Find(&repos)
  1138. if err != nil {
  1139. return nil, err
  1140. }
  1141. return repos, nil
  1142. }
  1143. // SyncExternalUsers is used to synchronize users with external authorization source
  1144. func SyncExternalUsers() {
  1145. if taskStatusTable.IsRunning(syncExternalUsers) {
  1146. return
  1147. }
  1148. taskStatusTable.Start(syncExternalUsers)
  1149. defer taskStatusTable.Stop(syncExternalUsers)
  1150. log.Trace("Doing: SyncExternalUsers")
  1151. ls, err := LoginSources()
  1152. if err != nil {
  1153. log.Error(4, "SyncExternalUsers: %v", err)
  1154. return
  1155. }
  1156. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1157. for _, s := range ls {
  1158. if !s.IsActived || !s.IsSyncEnabled {
  1159. continue
  1160. }
  1161. if s.IsLDAP() {
  1162. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1163. var existingUsers []int64
  1164. // Find all users with this login type
  1165. var users []User
  1166. x.Where("login_type = ?", LoginLDAP).
  1167. And("login_source = ?", s.ID).
  1168. Find(&users)
  1169. sr := s.LDAP().SearchEntries()
  1170. for _, su := range sr {
  1171. if len(su.Username) == 0 {
  1172. continue
  1173. }
  1174. if len(su.Mail) == 0 {
  1175. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1176. }
  1177. var usr *User
  1178. // Search for existing user
  1179. for _, du := range users {
  1180. if du.LowerName == strings.ToLower(su.Username) {
  1181. usr = &du
  1182. break
  1183. }
  1184. }
  1185. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1186. // If no existing user found, create one
  1187. if usr == nil {
  1188. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1189. usr = &User{
  1190. LowerName: strings.ToLower(su.Username),
  1191. Name: su.Username,
  1192. FullName: fullName,
  1193. LoginType: s.Type,
  1194. LoginSource: s.ID,
  1195. LoginName: su.Username,
  1196. Email: su.Mail,
  1197. IsAdmin: su.IsAdmin,
  1198. IsActive: true,
  1199. }
  1200. err = CreateUser(usr)
  1201. if err != nil {
  1202. log.Error(4, "SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1203. }
  1204. } else if updateExisting {
  1205. existingUsers = append(existingUsers, usr.ID)
  1206. // Check if user data has changed
  1207. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1208. strings.ToLower(usr.Email) != strings.ToLower(su.Mail) ||
  1209. usr.FullName != fullName ||
  1210. !usr.IsActive {
  1211. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1212. usr.FullName = fullName
  1213. usr.Email = su.Mail
  1214. // Change existing admin flag only if AdminFilter option is set
  1215. if len(s.LDAP().AdminFilter) > 0 {
  1216. usr.IsAdmin = su.IsAdmin
  1217. }
  1218. usr.IsActive = true
  1219. err = UpdateUser(usr)
  1220. if err != nil {
  1221. log.Error(4, "SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1222. }
  1223. }
  1224. }
  1225. }
  1226. // Deactivate users not present in LDAP
  1227. if updateExisting {
  1228. for _, usr := range users {
  1229. found := false
  1230. for _, uid := range existingUsers {
  1231. if usr.ID == uid {
  1232. found = true
  1233. break
  1234. }
  1235. }
  1236. if !found {
  1237. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1238. usr.IsActive = false
  1239. err = UpdateUser(&usr)
  1240. if err != nil {
  1241. log.Error(4, "SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1242. }
  1243. }
  1244. }
  1245. }
  1246. }
  1247. }
  1248. }