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 41 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
11 years ago
8 years ago
11 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
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
8 years ago
8 years ago
10 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 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
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
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
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
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  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/setting"
  34. "code.gitea.io/gitea/modules/util"
  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. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  81. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  82. LastLoginUnix util.TimeStamp `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 `xorm:"NOT NULL DEFAULT false"`
  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. // BeforeUpdate is invoked from XORM before updating this object.
  113. func (u *User) BeforeUpdate() {
  114. if u.MaxRepoCreation < -1 {
  115. u.MaxRepoCreation = -1
  116. }
  117. }
  118. // SetLastLogin set time to last login
  119. func (u *User) SetLastLogin() {
  120. u.LastLoginUnix = util.TimeStampNow()
  121. }
  122. // UpdateDiffViewStyle updates the users diff view style
  123. func (u *User) UpdateDiffViewStyle(style string) error {
  124. u.DiffViewStyle = style
  125. return UpdateUserCols(u, "diff_view_style")
  126. }
  127. /*
  128. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  129. func (u *User) AfterLoad() {
  130. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  131. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  132. u.LastLogin = time.Unix(u.LastLoginUnix, 0).Local()
  133. }*/
  134. // getEmail returns an noreply email, if the user has set to keep his
  135. // email address private, otherwise the primary email address.
  136. func (u *User) getEmail() string {
  137. if u.KeepEmailPrivate {
  138. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  139. }
  140. return u.Email
  141. }
  142. // APIFormat converts a User to api.User
  143. func (u *User) APIFormat() *api.User {
  144. return &api.User{
  145. ID: u.ID,
  146. UserName: u.Name,
  147. FullName: u.FullName,
  148. Email: u.getEmail(),
  149. AvatarURL: u.AvatarLink(),
  150. }
  151. }
  152. // IsLocal returns true if user login type is LoginPlain.
  153. func (u *User) IsLocal() bool {
  154. return u.LoginType <= LoginPlain
  155. }
  156. // IsOAuth2 returns true if user login type is LoginOAuth2.
  157. func (u *User) IsOAuth2() bool {
  158. return u.LoginType == LoginOAuth2
  159. }
  160. // HasForkedRepo checks if user has already forked a repository with given ID.
  161. func (u *User) HasForkedRepo(repoID int64) bool {
  162. _, has := HasForkedRepo(u.ID, repoID)
  163. return has
  164. }
  165. // MaxCreationLimit returns the number of repositories a user is allowed to create
  166. func (u *User) MaxCreationLimit() int {
  167. if u.MaxRepoCreation <= -1 {
  168. return setting.Repository.MaxCreationLimit
  169. }
  170. return u.MaxRepoCreation
  171. }
  172. // CanCreateRepo returns if user login can create a repository
  173. func (u *User) CanCreateRepo() bool {
  174. if u.IsAdmin {
  175. return true
  176. }
  177. if u.MaxRepoCreation <= -1 {
  178. if setting.Repository.MaxCreationLimit <= -1 {
  179. return true
  180. }
  181. return u.NumRepos < setting.Repository.MaxCreationLimit
  182. }
  183. return u.NumRepos < u.MaxRepoCreation
  184. }
  185. // CanCreateOrganization returns true if user can create organisation.
  186. func (u *User) CanCreateOrganization() bool {
  187. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  188. }
  189. // CanEditGitHook returns true if user can edit Git hooks.
  190. func (u *User) CanEditGitHook() bool {
  191. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  192. }
  193. // CanImportLocal returns true if user can migrate repository by local path.
  194. func (u *User) CanImportLocal() bool {
  195. if !setting.ImportLocalPaths {
  196. return false
  197. }
  198. return u.IsAdmin || u.AllowImportLocal
  199. }
  200. // DashboardLink returns the user dashboard page link.
  201. func (u *User) DashboardLink() string {
  202. if u.IsOrganization() {
  203. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  204. }
  205. return setting.AppSubURL + "/"
  206. }
  207. // HomeLink returns the user or organization home page link.
  208. func (u *User) HomeLink() string {
  209. return setting.AppSubURL + "/" + u.Name
  210. }
  211. // HTMLURL returns the user or organization's full link.
  212. func (u *User) HTMLURL() string {
  213. return setting.AppURL + u.Name
  214. }
  215. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  216. func (u *User) GenerateEmailActivateCode(email string) string {
  217. code := base.CreateTimeLimitCode(
  218. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  219. setting.Service.ActiveCodeLives, nil)
  220. // Add tail hex username
  221. code += hex.EncodeToString([]byte(u.LowerName))
  222. return code
  223. }
  224. // GenerateActivateCode generates an activate code based on user information.
  225. func (u *User) GenerateActivateCode() string {
  226. return u.GenerateEmailActivateCode(u.Email)
  227. }
  228. // CustomAvatarPath returns user custom avatar file path.
  229. func (u *User) CustomAvatarPath() string {
  230. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  231. }
  232. // GenerateRandomAvatar generates a random avatar for user.
  233. func (u *User) GenerateRandomAvatar() error {
  234. return u.generateRandomAvatar(x)
  235. }
  236. func (u *User) generateRandomAvatar(e Engine) error {
  237. seed := u.Email
  238. if len(seed) == 0 {
  239. seed = u.Name
  240. }
  241. img, err := avatar.RandomImage([]byte(seed))
  242. if err != nil {
  243. return fmt.Errorf("RandomImage: %v", err)
  244. }
  245. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  246. // since random image is not a user's photo, there is no security for enumable
  247. u.Avatar = fmt.Sprintf("%d", u.ID)
  248. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  249. return fmt.Errorf("MkdirAll: %v", err)
  250. }
  251. fw, err := os.Create(u.CustomAvatarPath())
  252. if err != nil {
  253. return fmt.Errorf("Create: %v", err)
  254. }
  255. defer fw.Close()
  256. if _, err := e.ID(u.ID).Cols("avatar").Update(u); err != nil {
  257. return err
  258. }
  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. // SizedRelAvatarLink returns a relative link to the user's avatar. When
  266. // applicable, the link is for an avatar of the indicated size (in pixels).
  267. func (u *User) SizedRelAvatarLink(size int) string {
  268. if u.ID == -1 {
  269. return base.DefaultAvatarLink()
  270. }
  271. switch {
  272. case u.UseCustomAvatar:
  273. if !com.IsFile(u.CustomAvatarPath()) {
  274. return base.DefaultAvatarLink()
  275. }
  276. return setting.AppSubURL + "/avatars/" + u.Avatar
  277. case setting.DisableGravatar, setting.OfflineMode:
  278. if !com.IsFile(u.CustomAvatarPath()) {
  279. if err := u.GenerateRandomAvatar(); err != nil {
  280. log.Error(3, "GenerateRandomAvatar: %v", err)
  281. }
  282. }
  283. return setting.AppSubURL + "/avatars/" + u.Avatar
  284. }
  285. return base.SizedAvatarLink(u.AvatarEmail, size)
  286. }
  287. // RelAvatarLink returns a relative link to the user's avatar. The link
  288. // may either be a sub-URL to this site, or a full URL to an external avatar
  289. // service.
  290. func (u *User) RelAvatarLink() string {
  291. return u.SizedRelAvatarLink(base.DefaultAvatarSize)
  292. }
  293. // AvatarLink returns user avatar absolute link.
  294. func (u *User) AvatarLink() string {
  295. link := u.RelAvatarLink()
  296. if link[0] == '/' && link[1] != '/' {
  297. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  298. }
  299. return link
  300. }
  301. // GetFollowers returns range of user's followers.
  302. func (u *User) GetFollowers(page int) ([]*User, error) {
  303. users := make([]*User, 0, ItemsPerPage)
  304. sess := x.
  305. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  306. Where("follow.follow_id=?", u.ID)
  307. if setting.UsePostgreSQL {
  308. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  309. } else {
  310. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  311. }
  312. return users, sess.Find(&users)
  313. }
  314. // IsFollowing returns true if user is following followID.
  315. func (u *User) IsFollowing(followID int64) bool {
  316. return IsFollowing(u.ID, followID)
  317. }
  318. // GetFollowing returns range of user's following.
  319. func (u *User) GetFollowing(page int) ([]*User, error) {
  320. users := make([]*User, 0, ItemsPerPage)
  321. sess := x.
  322. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  323. Where("follow.user_id=?", u.ID)
  324. if setting.UsePostgreSQL {
  325. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  326. } else {
  327. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  328. }
  329. return users, sess.Find(&users)
  330. }
  331. // NewGitSig generates and returns the signature of given user.
  332. func (u *User) NewGitSig() *git.Signature {
  333. return &git.Signature{
  334. Name: u.DisplayName(),
  335. Email: u.getEmail(),
  336. When: time.Now(),
  337. }
  338. }
  339. // EncodePasswd encodes password to safe format.
  340. func (u *User) EncodePasswd() {
  341. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  342. u.Passwd = fmt.Sprintf("%x", newPasswd)
  343. }
  344. // ValidatePassword checks if given password matches the one belongs to the user.
  345. func (u *User) ValidatePassword(passwd string) bool {
  346. newUser := &User{Passwd: passwd, Salt: u.Salt}
  347. newUser.EncodePasswd()
  348. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  349. }
  350. // IsPasswordSet checks if the password is set or left empty
  351. func (u *User) IsPasswordSet() bool {
  352. return !u.ValidatePassword("")
  353. }
  354. // UploadAvatar saves custom avatar for user.
  355. // FIXME: split uploads to different subdirs in case we have massive users.
  356. func (u *User) UploadAvatar(data []byte) error {
  357. img, _, err := image.Decode(bytes.NewReader(data))
  358. if err != nil {
  359. return fmt.Errorf("Decode: %v", err)
  360. }
  361. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  362. sess := x.NewSession()
  363. defer sess.Close()
  364. if err = sess.Begin(); err != nil {
  365. return err
  366. }
  367. u.UseCustomAvatar = true
  368. u.Avatar = fmt.Sprintf("%x", md5.Sum(data))
  369. if err = updateUser(sess, u); err != nil {
  370. return fmt.Errorf("updateUser: %v", err)
  371. }
  372. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  373. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  374. }
  375. fw, err := os.Create(u.CustomAvatarPath())
  376. if err != nil {
  377. return fmt.Errorf("Create: %v", err)
  378. }
  379. defer fw.Close()
  380. if err = png.Encode(fw, m); err != nil {
  381. return fmt.Errorf("Encode: %v", err)
  382. }
  383. return sess.Commit()
  384. }
  385. // DeleteAvatar deletes the user's custom avatar.
  386. func (u *User) DeleteAvatar() error {
  387. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  388. if len(u.Avatar) > 0 {
  389. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  390. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  391. }
  392. }
  393. u.UseCustomAvatar = false
  394. u.Avatar = ""
  395. if _, err := x.ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  396. return fmt.Errorf("UpdateUser: %v", err)
  397. }
  398. return nil
  399. }
  400. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  401. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  402. has, err := HasAccess(u.ID, repo, AccessModeAdmin)
  403. if err != nil {
  404. log.Error(3, "HasAccess: %v", err)
  405. }
  406. return has
  407. }
  408. // IsWriterOfRepo returns true if user has write access to given repository.
  409. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  410. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  411. if err != nil {
  412. log.Error(3, "HasAccess: %v", err)
  413. }
  414. return has
  415. }
  416. // IsOrganization returns true if user is actually a organization.
  417. func (u *User) IsOrganization() bool {
  418. return u.Type == UserTypeOrganization
  419. }
  420. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  421. func (u *User) IsUserOrgOwner(orgID int64) bool {
  422. return IsOrganizationOwner(orgID, u.ID)
  423. }
  424. // IsPublicMember returns true if user public his/her membership in given organization.
  425. func (u *User) IsPublicMember(orgID int64) bool {
  426. return IsPublicMembership(orgID, u.ID)
  427. }
  428. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  429. return e.
  430. Where("uid=?", u.ID).
  431. Count(new(OrgUser))
  432. }
  433. // GetOrganizationCount returns count of membership of organization of user.
  434. func (u *User) GetOrganizationCount() (int64, error) {
  435. return u.getOrganizationCount(x)
  436. }
  437. // GetRepositories returns repositories that user owns, including private repositories.
  438. func (u *User) GetRepositories(page, pageSize int) (err error) {
  439. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  440. return err
  441. }
  442. // GetRepositoryIDs returns repositories IDs where user owned
  443. func (u *User) GetRepositoryIDs() ([]int64, error) {
  444. var ids []int64
  445. return ids, x.Table("repository").Cols("id").Where("owner_id = ?", u.ID).Find(&ids)
  446. }
  447. // GetOrgRepositoryIDs returns repositories IDs where user's team owned
  448. func (u *User) GetOrgRepositoryIDs() ([]int64, error) {
  449. var ids []int64
  450. return ids, x.Table("repository").
  451. Cols("repository.id").
  452. Join("INNER", "team_user", "repository.owner_id = team_user.org_id AND team_user.uid = ?", u.ID).
  453. GroupBy("repository.id").Find(&ids)
  454. }
  455. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  456. func (u *User) GetAccessRepoIDs() ([]int64, error) {
  457. ids, err := u.GetRepositoryIDs()
  458. if err != nil {
  459. return nil, err
  460. }
  461. ids2, err := u.GetOrgRepositoryIDs()
  462. if err != nil {
  463. return nil, err
  464. }
  465. return append(ids, ids2...), nil
  466. }
  467. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  468. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  469. return GetUserMirrorRepositories(u.ID)
  470. }
  471. // GetOwnedOrganizations returns all organizations that user owns.
  472. func (u *User) GetOwnedOrganizations() (err error) {
  473. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  474. return err
  475. }
  476. // GetOrganizations returns all organizations that user belongs to.
  477. func (u *User) GetOrganizations(all bool) error {
  478. ous, err := GetOrgUsersByUserID(u.ID, all)
  479. if err != nil {
  480. return err
  481. }
  482. u.Orgs = make([]*User, len(ous))
  483. for i, ou := range ous {
  484. u.Orgs[i], err = GetUserByID(ou.OrgID)
  485. if err != nil {
  486. return err
  487. }
  488. }
  489. return nil
  490. }
  491. // DisplayName returns full name if it's not empty,
  492. // returns username otherwise.
  493. func (u *User) DisplayName() string {
  494. if len(u.FullName) > 0 {
  495. return u.FullName
  496. }
  497. return u.Name
  498. }
  499. // ShortName ellipses username to length
  500. func (u *User) ShortName(length int) string {
  501. return base.EllipsisString(u.Name, length)
  502. }
  503. // IsMailable checks if a user is eligible
  504. // to receive emails.
  505. func (u *User) IsMailable() bool {
  506. return u.IsActive
  507. }
  508. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  509. if len(name) == 0 {
  510. return false, nil
  511. }
  512. return e.
  513. Where("id!=?", uid).
  514. Get(&User{LowerName: strings.ToLower(name)})
  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. return isUserExist(x, uid, name)
  522. }
  523. // GetUserSalt returns a random user salt token.
  524. func GetUserSalt() (string, error) {
  525. return base.GetRandomString(10)
  526. }
  527. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  528. func NewGhostUser() *User {
  529. return &User{
  530. ID: -1,
  531. Name: "Ghost",
  532. LowerName: "ghost",
  533. }
  534. }
  535. var (
  536. 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", ".", ".."}
  537. reservedUserPatterns = []string{"*.keys"}
  538. )
  539. // isUsableName checks if name is reserved or pattern of name is not allowed
  540. // based on given reserved names and patterns.
  541. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  542. func isUsableName(names, patterns []string, name string) error {
  543. name = strings.TrimSpace(strings.ToLower(name))
  544. if utf8.RuneCountInString(name) == 0 {
  545. return ErrNameEmpty
  546. }
  547. for i := range names {
  548. if name == names[i] {
  549. return ErrNameReserved{name}
  550. }
  551. }
  552. for _, pat := range patterns {
  553. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  554. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  555. return ErrNamePatternNotAllowed{pat}
  556. }
  557. }
  558. return nil
  559. }
  560. // IsUsableUsername returns an error when a username is reserved
  561. func IsUsableUsername(name string) error {
  562. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  563. }
  564. // CreateUser creates record of a new user.
  565. func CreateUser(u *User) (err error) {
  566. if err = IsUsableUsername(u.Name); err != nil {
  567. return err
  568. }
  569. sess := x.NewSession()
  570. defer sess.Close()
  571. if err = sess.Begin(); err != nil {
  572. return err
  573. }
  574. isExist, err := isUserExist(sess, 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. isExist, err = sess.
  582. Where("email=?", u.Email).
  583. Get(new(User))
  584. if err != nil {
  585. return err
  586. } else if isExist {
  587. return ErrEmailAlreadyUsed{u.Email}
  588. }
  589. isExist, err = isEmailUsed(sess, 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. if _, err = sess.Insert(u); err != nil {
  609. return err
  610. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  611. return err
  612. }
  613. return sess.Commit()
  614. }
  615. func countUsers(e Engine) int64 {
  616. count, _ := e.
  617. Where("type=0").
  618. Count(new(User))
  619. return count
  620. }
  621. // CountUsers returns number of users.
  622. func CountUsers() int64 {
  623. return countUsers(x)
  624. }
  625. // get user by verify code
  626. func getVerifyUser(code string) (user *User) {
  627. if len(code) <= base.TimeLimitCodeLength {
  628. return nil
  629. }
  630. // use tail hex username query user
  631. hexStr := code[base.TimeLimitCodeLength:]
  632. if b, err := hex.DecodeString(hexStr); err == nil {
  633. if user, err = GetUserByName(string(b)); user != nil {
  634. return user
  635. }
  636. log.Error(4, "user.getVerifyUser: %v", err)
  637. }
  638. return nil
  639. }
  640. // VerifyUserActiveCode verifies active code when active account
  641. func VerifyUserActiveCode(code string) (user *User) {
  642. minutes := setting.Service.ActiveCodeLives
  643. if user = getVerifyUser(code); user != nil {
  644. // time limit code
  645. prefix := code[:base.TimeLimitCodeLength]
  646. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  647. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  648. return user
  649. }
  650. }
  651. return nil
  652. }
  653. // VerifyActiveEmailCode verifies active email code when active account
  654. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  655. minutes := setting.Service.ActiveCodeLives
  656. if user := getVerifyUser(code); user != nil {
  657. // time limit code
  658. prefix := code[:base.TimeLimitCodeLength]
  659. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  660. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  661. emailAddress := &EmailAddress{Email: email}
  662. if has, _ := x.Get(emailAddress); has {
  663. return emailAddress
  664. }
  665. }
  666. }
  667. return nil
  668. }
  669. // ChangeUserName changes all corresponding setting from old user name to new one.
  670. func ChangeUserName(u *User, newUserName string) (err error) {
  671. if err = IsUsableUsername(newUserName); err != nil {
  672. return err
  673. }
  674. isExist, err := IsUserExist(0, newUserName)
  675. if err != nil {
  676. return err
  677. } else if isExist {
  678. return ErrUserAlreadyExist{newUserName}
  679. }
  680. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  681. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  682. }
  683. // Delete all local copies of repository wiki that user owns.
  684. if err = x.BufferSize(setting.IterateBufferSize).
  685. Where("owner_id=?", u.ID).
  686. Iterate(new(Repository), func(idx int, bean interface{}) error {
  687. repo := bean.(*Repository)
  688. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  689. return nil
  690. }); err != nil {
  691. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  692. }
  693. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  694. }
  695. // checkDupEmail checks whether there are the same email with the user
  696. func checkDupEmail(e Engine, u *User) error {
  697. u.Email = strings.ToLower(u.Email)
  698. has, err := e.
  699. Where("id!=?", u.ID).
  700. And("type=?", u.Type).
  701. And("email=?", u.Email).
  702. Get(new(User))
  703. if err != nil {
  704. return err
  705. } else if has {
  706. return ErrEmailAlreadyUsed{u.Email}
  707. }
  708. return nil
  709. }
  710. func updateUser(e Engine, u *User) error {
  711. // Organization does not need email
  712. u.Email = strings.ToLower(u.Email)
  713. if !u.IsOrganization() {
  714. if len(u.AvatarEmail) == 0 {
  715. u.AvatarEmail = u.Email
  716. }
  717. if len(u.AvatarEmail) > 0 {
  718. u.Avatar = base.HashEmail(u.AvatarEmail)
  719. }
  720. }
  721. u.LowerName = strings.ToLower(u.Name)
  722. u.Location = base.TruncateString(u.Location, 255)
  723. u.Website = base.TruncateString(u.Website, 255)
  724. u.Description = base.TruncateString(u.Description, 255)
  725. _, err := e.ID(u.ID).AllCols().Update(u)
  726. return err
  727. }
  728. // UpdateUser updates user's information.
  729. func UpdateUser(u *User) error {
  730. return updateUser(x, u)
  731. }
  732. // UpdateUserCols update user according special columns
  733. func UpdateUserCols(u *User, cols ...string) error {
  734. return updateUserCols(x, u, cols...)
  735. }
  736. func updateUserCols(e Engine, u *User, cols ...string) error {
  737. // Organization does not need email
  738. u.Email = strings.ToLower(u.Email)
  739. if !u.IsOrganization() {
  740. if len(u.AvatarEmail) == 0 {
  741. u.AvatarEmail = u.Email
  742. }
  743. if len(u.AvatarEmail) > 0 {
  744. u.Avatar = base.HashEmail(u.AvatarEmail)
  745. }
  746. }
  747. u.LowerName = strings.ToLower(u.Name)
  748. u.Location = base.TruncateString(u.Location, 255)
  749. u.Website = base.TruncateString(u.Website, 255)
  750. u.Description = base.TruncateString(u.Description, 255)
  751. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  752. return err
  753. }
  754. // UpdateUserSetting updates user's settings.
  755. func UpdateUserSetting(u *User) error {
  756. if !u.IsOrganization() {
  757. if err := checkDupEmail(x, u); err != nil {
  758. return err
  759. }
  760. }
  761. return updateUser(x, u)
  762. }
  763. // deleteBeans deletes all given beans, beans should contain delete conditions.
  764. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  765. for i := range beans {
  766. if _, err = e.Delete(beans[i]); err != nil {
  767. return err
  768. }
  769. }
  770. return nil
  771. }
  772. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  773. func deleteUser(e *xorm.Session, u *User) error {
  774. // Note: A user owns any repository or belongs to any organization
  775. // cannot perform delete operation.
  776. // Check ownership of repository.
  777. count, err := getRepositoryCount(e, u)
  778. if err != nil {
  779. return fmt.Errorf("GetRepositoryCount: %v", err)
  780. } else if count > 0 {
  781. return ErrUserOwnRepos{UID: u.ID}
  782. }
  783. // Check membership of organization.
  784. count, err = u.getOrganizationCount(e)
  785. if err != nil {
  786. return fmt.Errorf("GetOrganizationCount: %v", err)
  787. } else if count > 0 {
  788. return ErrUserHasOrgs{UID: u.ID}
  789. }
  790. // ***** START: Watch *****
  791. watchedRepoIDs := make([]int64, 0, 10)
  792. if err = e.Table("watch").Cols("watch.repo_id").
  793. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  794. return fmt.Errorf("get all watches: %v", err)
  795. }
  796. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).Update(new(Repository)); err != nil {
  797. return fmt.Errorf("decrease repository num_watches: %v", err)
  798. }
  799. // ***** END: Watch *****
  800. // ***** START: Star *****
  801. starredRepoIDs := make([]int64, 0, 10)
  802. if err = e.Table("star").Cols("star.repo_id").
  803. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  804. return fmt.Errorf("get all stars: %v", err)
  805. } else if _, err = e.Decr("num_watches").In("id", starredRepoIDs).Update(new(Repository)); err != nil {
  806. return fmt.Errorf("decrease repository num_stars: %v", err)
  807. }
  808. // ***** END: Star *****
  809. // ***** START: Follow *****
  810. followeeIDs := make([]int64, 0, 10)
  811. if err = e.Table("follow").Cols("follow.follow_id").
  812. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  813. return fmt.Errorf("get all followees: %v", err)
  814. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  815. return fmt.Errorf("decrease user num_followers: %v", err)
  816. }
  817. followerIDs := make([]int64, 0, 10)
  818. if err = e.Table("follow").Cols("follow.user_id").
  819. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  820. return fmt.Errorf("get all followers: %v", err)
  821. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  822. return fmt.Errorf("decrease user num_following: %v", err)
  823. }
  824. // ***** END: Follow *****
  825. if err = deleteBeans(e,
  826. &AccessToken{UID: u.ID},
  827. &Collaboration{UserID: u.ID},
  828. &Access{UserID: u.ID},
  829. &Watch{UserID: u.ID},
  830. &Star{UID: u.ID},
  831. &Follow{UserID: u.ID},
  832. &Follow{FollowID: u.ID},
  833. &Action{UserID: u.ID},
  834. &IssueUser{UID: u.ID},
  835. &EmailAddress{UID: u.ID},
  836. &UserOpenID{UID: u.ID},
  837. &Reaction{UserID: u.ID},
  838. ); err != nil {
  839. return fmt.Errorf("deleteBeans: %v", err)
  840. }
  841. // ***** START: PublicKey *****
  842. keys := make([]*PublicKey, 0, 10)
  843. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  844. return fmt.Errorf("get all public keys: %v", err)
  845. }
  846. keyIDs := make([]int64, len(keys))
  847. for i := range keys {
  848. keyIDs[i] = keys[i].ID
  849. }
  850. if err = deletePublicKeys(e, keyIDs...); err != nil {
  851. return fmt.Errorf("deletePublicKeys: %v", err)
  852. }
  853. // ***** END: PublicKey *****
  854. // Clear assignee.
  855. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  856. return fmt.Errorf("clear assignee: %v", err)
  857. }
  858. // ***** START: ExternalLoginUser *****
  859. if err = removeAllAccountLinks(e, u); err != nil {
  860. return fmt.Errorf("ExternalLoginUser: %v", err)
  861. }
  862. // ***** END: ExternalLoginUser *****
  863. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  864. return fmt.Errorf("Delete: %v", err)
  865. }
  866. // FIXME: system notice
  867. // Note: There are something just cannot be roll back,
  868. // so just keep error logs of those operations.
  869. path := UserPath(u.Name)
  870. if err := os.RemoveAll(path); err != nil {
  871. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  872. }
  873. if len(u.Avatar) > 0 {
  874. avatarPath := u.CustomAvatarPath()
  875. if com.IsExist(avatarPath) {
  876. if err := os.Remove(avatarPath); err != nil {
  877. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  878. }
  879. }
  880. }
  881. return nil
  882. }
  883. // DeleteUser completely and permanently deletes everything of a user,
  884. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  885. func DeleteUser(u *User) (err error) {
  886. sess := x.NewSession()
  887. defer sess.Close()
  888. if err = sess.Begin(); err != nil {
  889. return err
  890. }
  891. if err = deleteUser(sess, u); err != nil {
  892. // Note: don't wrapper error here.
  893. return err
  894. }
  895. if err = sess.Commit(); err != nil {
  896. return err
  897. }
  898. return RewriteAllPublicKeys()
  899. }
  900. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  901. func DeleteInactivateUsers() (err error) {
  902. users := make([]*User, 0, 10)
  903. if err = x.
  904. Where("is_active = ?", false).
  905. Find(&users); err != nil {
  906. return fmt.Errorf("get all inactive users: %v", err)
  907. }
  908. // FIXME: should only update authorized_keys file once after all deletions.
  909. for _, u := range users {
  910. if err = DeleteUser(u); err != nil {
  911. // Ignore users that were set inactive by admin.
  912. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  913. continue
  914. }
  915. return err
  916. }
  917. }
  918. _, err = x.
  919. Where("is_activated = ?", false).
  920. Delete(new(EmailAddress))
  921. return err
  922. }
  923. // UserPath returns the path absolute path of user repositories.
  924. func UserPath(userName string) string {
  925. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  926. }
  927. // GetUserByKeyID get user information by user's public key id
  928. func GetUserByKeyID(keyID int64) (*User, error) {
  929. var user User
  930. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  931. Where("`public_key`.id=?", keyID).
  932. Get(&user)
  933. if err != nil {
  934. return nil, err
  935. }
  936. if !has {
  937. return nil, ErrUserNotExist{0, "", keyID}
  938. }
  939. return &user, nil
  940. }
  941. func getUserByID(e Engine, id int64) (*User, error) {
  942. u := new(User)
  943. has, err := e.ID(id).Get(u)
  944. if err != nil {
  945. return nil, err
  946. } else if !has {
  947. return nil, ErrUserNotExist{id, "", 0}
  948. }
  949. return u, nil
  950. }
  951. // GetUserByID returns the user object by given ID if exists.
  952. func GetUserByID(id int64) (*User, error) {
  953. return getUserByID(x, id)
  954. }
  955. // GetAssigneeByID returns the user with write access of repository by given ID.
  956. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  957. has, err := HasAccess(userID, repo, AccessModeWrite)
  958. if err != nil {
  959. return nil, err
  960. } else if !has {
  961. return nil, ErrUserNotExist{userID, "", 0}
  962. }
  963. return GetUserByID(userID)
  964. }
  965. // GetUserByName returns user by given name.
  966. func GetUserByName(name string) (*User, error) {
  967. return getUserByName(x, name)
  968. }
  969. func getUserByName(e Engine, name string) (*User, error) {
  970. if len(name) == 0 {
  971. return nil, ErrUserNotExist{0, name, 0}
  972. }
  973. u := &User{LowerName: strings.ToLower(name)}
  974. has, err := e.Get(u)
  975. if err != nil {
  976. return nil, err
  977. } else if !has {
  978. return nil, ErrUserNotExist{0, name, 0}
  979. }
  980. return u, nil
  981. }
  982. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  983. func GetUserEmailsByNames(names []string) []string {
  984. return getUserEmailsByNames(x, names)
  985. }
  986. func getUserEmailsByNames(e Engine, names []string) []string {
  987. mails := make([]string, 0, len(names))
  988. for _, name := range names {
  989. u, err := getUserByName(e, name)
  990. if err != nil {
  991. continue
  992. }
  993. if u.IsMailable() {
  994. mails = append(mails, u.Email)
  995. }
  996. }
  997. return mails
  998. }
  999. // GetUsersByIDs returns all resolved users from a list of Ids.
  1000. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1001. ous := make([]*User, 0, len(ids))
  1002. if len(ids) == 0 {
  1003. return ous, nil
  1004. }
  1005. err := x.In("id", ids).
  1006. Asc("name").
  1007. Find(&ous)
  1008. return ous, err
  1009. }
  1010. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1011. func GetUserIDsByNames(names []string) []int64 {
  1012. ids := make([]int64, 0, len(names))
  1013. for _, name := range names {
  1014. u, err := GetUserByName(name)
  1015. if err != nil {
  1016. continue
  1017. }
  1018. ids = append(ids, u.ID)
  1019. }
  1020. return ids
  1021. }
  1022. // UserCommit represents a commit with validation of user.
  1023. type UserCommit struct {
  1024. User *User
  1025. *git.Commit
  1026. }
  1027. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1028. func ValidateCommitWithEmail(c *git.Commit) *User {
  1029. if c.Author == nil {
  1030. return nil
  1031. }
  1032. u, err := GetUserByEmail(c.Author.Email)
  1033. if err != nil {
  1034. return nil
  1035. }
  1036. return u
  1037. }
  1038. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1039. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1040. var (
  1041. u *User
  1042. emails = map[string]*User{}
  1043. newCommits = list.New()
  1044. e = oldCommits.Front()
  1045. )
  1046. for e != nil {
  1047. c := e.Value.(*git.Commit)
  1048. if c.Author != nil {
  1049. if v, ok := emails[c.Author.Email]; !ok {
  1050. u, _ = GetUserByEmail(c.Author.Email)
  1051. emails[c.Author.Email] = u
  1052. } else {
  1053. u = v
  1054. }
  1055. } else {
  1056. u = nil
  1057. }
  1058. newCommits.PushBack(UserCommit{
  1059. User: u,
  1060. Commit: c,
  1061. })
  1062. e = e.Next()
  1063. }
  1064. return newCommits
  1065. }
  1066. // GetUserByEmail returns the user object by given e-mail if exists.
  1067. func GetUserByEmail(email string) (*User, error) {
  1068. if len(email) == 0 {
  1069. return nil, ErrUserNotExist{0, email, 0}
  1070. }
  1071. email = strings.ToLower(email)
  1072. // First try to find the user by primary email
  1073. user := &User{Email: email}
  1074. has, err := x.Get(user)
  1075. if err != nil {
  1076. return nil, err
  1077. }
  1078. if has {
  1079. return user, nil
  1080. }
  1081. // Otherwise, check in alternative list for activated email addresses
  1082. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1083. has, err = x.Get(emailAddress)
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. if has {
  1088. return GetUserByID(emailAddress.UID)
  1089. }
  1090. return nil, ErrUserNotExist{0, email, 0}
  1091. }
  1092. // GetUser checks if a user already exists
  1093. func GetUser(user *User) (bool, error) {
  1094. return x.Get(user)
  1095. }
  1096. // SearchUserOptions contains the options for searching
  1097. type SearchUserOptions struct {
  1098. Keyword string
  1099. Type UserType
  1100. OrderBy string
  1101. Page int
  1102. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1103. IsActive util.OptionalBool
  1104. SearchByEmail bool // Search by email as well as username/full name
  1105. }
  1106. func (opts *SearchUserOptions) toConds() builder.Cond {
  1107. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1108. if len(opts.Keyword) > 0 {
  1109. lowerKeyword := strings.ToLower(opts.Keyword)
  1110. keywordCond := builder.Or(
  1111. builder.Like{"lower_name", lowerKeyword},
  1112. builder.Like{"LOWER(full_name)", lowerKeyword},
  1113. )
  1114. if opts.SearchByEmail {
  1115. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1116. }
  1117. cond = cond.And(keywordCond)
  1118. }
  1119. if !opts.IsActive.IsNone() {
  1120. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1121. }
  1122. return cond
  1123. }
  1124. // SearchUsers takes options i.e. keyword and part of user name to search,
  1125. // it returns results in given range and number of total results.
  1126. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1127. cond := opts.toConds()
  1128. count, err := x.Where(cond).Count(new(User))
  1129. if err != nil {
  1130. return nil, 0, fmt.Errorf("Count: %v", err)
  1131. }
  1132. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1133. opts.PageSize = setting.UI.ExplorePagingNum
  1134. }
  1135. if opts.Page <= 0 {
  1136. opts.Page = 1
  1137. }
  1138. if len(opts.OrderBy) == 0 {
  1139. opts.OrderBy = "name ASC"
  1140. }
  1141. users = make([]*User, 0, opts.PageSize)
  1142. return users, count, x.Where(cond).
  1143. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  1144. OrderBy(opts.OrderBy).
  1145. Find(&users)
  1146. }
  1147. // GetStarredRepos returns the repos starred by a particular user
  1148. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1149. sess := x.Where("star.uid=?", userID).
  1150. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1151. if !private {
  1152. sess = sess.And("is_private=?", false)
  1153. }
  1154. repos := make([]*Repository, 0, 10)
  1155. err := sess.Find(&repos)
  1156. if err != nil {
  1157. return nil, err
  1158. }
  1159. return repos, nil
  1160. }
  1161. // GetWatchedRepos returns the repos watched by a particular user
  1162. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1163. sess := x.Where("watch.user_id=?", userID).
  1164. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1165. if !private {
  1166. sess = sess.And("is_private=?", false)
  1167. }
  1168. repos := make([]*Repository, 0, 10)
  1169. err := sess.Find(&repos)
  1170. if err != nil {
  1171. return nil, err
  1172. }
  1173. return repos, nil
  1174. }
  1175. // SyncExternalUsers is used to synchronize users with external authorization source
  1176. func SyncExternalUsers() {
  1177. if !taskStatusTable.StartIfNotRunning(syncExternalUsers) {
  1178. return
  1179. }
  1180. defer taskStatusTable.Stop(syncExternalUsers)
  1181. log.Trace("Doing: SyncExternalUsers")
  1182. ls, err := LoginSources()
  1183. if err != nil {
  1184. log.Error(4, "SyncExternalUsers: %v", err)
  1185. return
  1186. }
  1187. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1188. for _, s := range ls {
  1189. if !s.IsActived || !s.IsSyncEnabled {
  1190. continue
  1191. }
  1192. if s.IsLDAP() {
  1193. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1194. var existingUsers []int64
  1195. // Find all users with this login type
  1196. var users []User
  1197. x.Where("login_type = ?", LoginLDAP).
  1198. And("login_source = ?", s.ID).
  1199. Find(&users)
  1200. sr := s.LDAP().SearchEntries()
  1201. for _, su := range sr {
  1202. if len(su.Username) == 0 {
  1203. continue
  1204. }
  1205. if len(su.Mail) == 0 {
  1206. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1207. }
  1208. var usr *User
  1209. // Search for existing user
  1210. for _, du := range users {
  1211. if du.LowerName == strings.ToLower(su.Username) {
  1212. usr = &du
  1213. break
  1214. }
  1215. }
  1216. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1217. // If no existing user found, create one
  1218. if usr == nil {
  1219. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1220. usr = &User{
  1221. LowerName: strings.ToLower(su.Username),
  1222. Name: su.Username,
  1223. FullName: fullName,
  1224. LoginType: s.Type,
  1225. LoginSource: s.ID,
  1226. LoginName: su.Username,
  1227. Email: su.Mail,
  1228. IsAdmin: su.IsAdmin,
  1229. IsActive: true,
  1230. }
  1231. err = CreateUser(usr)
  1232. if err != nil {
  1233. log.Error(4, "SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1234. }
  1235. } else if updateExisting {
  1236. existingUsers = append(existingUsers, usr.ID)
  1237. // Check if user data has changed
  1238. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1239. strings.ToLower(usr.Email) != strings.ToLower(su.Mail) ||
  1240. usr.FullName != fullName ||
  1241. !usr.IsActive {
  1242. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1243. usr.FullName = fullName
  1244. usr.Email = su.Mail
  1245. // Change existing admin flag only if AdminFilter option is set
  1246. if len(s.LDAP().AdminFilter) > 0 {
  1247. usr.IsAdmin = su.IsAdmin
  1248. }
  1249. usr.IsActive = true
  1250. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1251. if err != nil {
  1252. log.Error(4, "SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1253. }
  1254. }
  1255. }
  1256. }
  1257. // Deactivate users not present in LDAP
  1258. if updateExisting {
  1259. for _, usr := range users {
  1260. found := false
  1261. for _, uid := range existingUsers {
  1262. if usr.ID == uid {
  1263. found = true
  1264. break
  1265. }
  1266. }
  1267. if !found {
  1268. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1269. usr.IsActive = false
  1270. err = UpdateUserCols(&usr, "is_active")
  1271. if err != nil {
  1272. log.Error(4, "SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. }