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 37 kB

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