File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change @@ -124,6 +124,7 @@ class CreateAccountRequest extends AuthRequest {
124124 let accountManager = this . accountManager
125125
126126 return Promise . resolve ( userAccount )
127+ . then ( this . cancelIfUsernameInvalid . bind ( this ) )
127128 . then ( this . cancelIfAccountExists . bind ( this ) )
128129 . then ( this . createAccountStorage . bind ( this ) )
129130 . then ( this . saveCredentialsFor . bind ( this ) )
@@ -186,6 +187,26 @@ class CreateAccountRequest extends AuthRequest {
186187 return userAccount
187188 } )
188189 }
190+
191+ /**
192+ * Check if a username is a valid slug.
193+ *
194+ * @param userAccount {UserAccount} Instance of the account to be created
195+ *
196+ * @throws {Error } If errors were encountering while validating the
197+ * username.
198+ *
199+ * @return {Promise<UserAccount> } Chainable
200+ */
201+ cancelIfUsernameInvalid ( userAccount ) {
202+ if ( ! userAccount . username || ! / ^ [ a - z 0 - 9 ] + (?: - [ a - z 0 - 9 ] + ) * $ / . test ( userAccount . username ) ) {
203+ const error = new Error ( 'Invalid username' )
204+ error . status = 400
205+ throw error
206+ }
207+
208+ return userAccount
209+ }
189210}
190211
191212/**
Original file line number Diff line number Diff line change @@ -84,6 +84,49 @@ describe('CreateAccountRequest', () => {
8484 done ( )
8585 } )
8686 } )
87+
88+ it ( 'should return a 400 error if a username is invalid' , ( ) => {
89+ let accountManager = AccountManager . from ( { host } )
90+ let locals = { authMethod : defaults . auth , accountManager, oidc : { users : { } } }
91+
92+ accountManager . accountExists = sinon . stub ( ) . returns ( Promise . resolve ( false ) )
93+
94+ const invalidUsernames = [
95+ '-' ,
96+ '-a' ,
97+ 'a-' ,
98+ '9-' ,
99+ 'alice--bob' ,
100+ 'alice bob' ,
101+ 'alice.bob'
102+ ]
103+
104+ let invalidUsernamesCount = 0
105+
106+ const requests = invalidUsernames . map ( ( username ) => {
107+ let aliceData = {
108+ username : username , password : '1234'
109+ }
110+
111+ let req = HttpMocks . createRequest ( { app : { locals } , body : aliceData } )
112+ let request = CreateAccountRequest . fromParams ( req , res )
113+
114+ return request . createAccount ( )
115+ . then ( ( ) => {
116+ throw new Error ( 'should not happen' )
117+ } )
118+ . catch ( err => {
119+ invalidUsernamesCount ++
120+ expect ( err . message ) . to . match ( / I n v a l i d u s e r n a m e / )
121+ expect ( err . status ) . to . equal ( 400 )
122+ } )
123+ } )
124+
125+ return Promise . all ( requests )
126+ . then ( ( ) => {
127+ expect ( invalidUsernamesCount ) . to . eq ( invalidUsernames . length )
128+ } )
129+ } )
87130 } )
88131} )
89132
You can’t perform that action at this time.
0 commit comments