def delete(self, environ, params): try: Controller().checkToken() if Controller().getApiType() != 1: output.error("Not your api business", 403) u = UserFactory.get(params["uid"]) if not u: output.error("user not found", 404) uid = params["uid"] blobId = BlobFactory.getBlobIds(user=params["uid"], release="published", type="avatar") if not len(blobId): output.error("avatar not found", 404) blobId = blobId.pop() BlobFactory.delete(blobId, "published") UserFactory.setAvatar(u.uid, False) output.success("avatar deleted", 200) except Error: pass return Controller().getResponse(True)
def list(self, environ, params): try: Controller().checkToken() me = Controller().getUid() apikey = Controller().getApiKey() u = UserFactory.get(me) if u.level < 3: output.error('forbidden', 403) users, total = UserFactory.getAllUsers() result = [] for user in users: profile = user.getProfile() uObject = user.toObject() uObject['profile'] = profile['datas'] result.append(uObject) output.success(result, 200) except Error: pass return Controller().getResponse(True)
def set(self, environ, params): try: Controller().checkToken() req = Controller().getRequest() router = Controller().getRouter() u = UserFactory.get(params["uid"]) if not u: output.error("user not found", 404) cT = req.headers["Content-Type"] or "application/octet-stream" blobId = BlobFactory.getBlobIds(user=params["uid"], release="published", type="avatar") if not len(blobId): blobId = BlobFactory.insert("avatar", "published", req.body, cT, user=params["uid"]) else: blobId = blobId[0] BlobFactory.update(blobId, "avatar", "published", req.body, cT, user=params["uid"]) UserFactory.setAvatar(u.uid, True) resultUrl = router.getRoute( "graph.Blob.fetch", {"version": params["version"], "bid": str(blobId), "release": "published"} ) output.success({"url": resultUrl, "blobId": str(blobId)}, 201) except Error: pass return Controller().getResponse(True)
def set(self, environ, params): try: Controller().checkToken() #relation = Controller().getRelation() me = Controller().getUid() apikey = Controller().getApiKey() if Controller().getApiType() != 1: output.error('Not your api business', 403) me = UserFactory.get(me) if me.level < 3: output.error('forbidden', 403) user = UserFactory.get(params['uid']) newLevel = params['role'] if newLevel == 'admin': user.level = 3 elif newLevel == 'reviewer': user.level = 2 else : user.level = 1 Db().get('users').update({'uid': user.uid}, user) output.success('acl changed', 200) except Error: pass return Controller().getResponse(True)
def reminderSend(self, environ, params): try: email = Controller().getRequest().GET['email'] if not email: output.error('need email', 400) user = UserFactory.get({'email': email}) if user is None: output.error('unknown user', 400) user.generatePasswordReminder() Db().get('users').update({'uid': user.uid}, user) #send mail AsyncMailer( template_name='password-reminder', template_content=[{ 'name': 'validation_code', 'content': user.password_reminder }], global_merge_vars=[ ], message={ 'subject': 'Mot de passe perdu Éducation et Numérique', 'from_email': '*****@*****.**', 'from_name': 'Education & Numérique', 'headers': {}, 'to': [ { 'email': user.email, 'name': user.username } ], 'metadata': { 'uid': user.uid, 'email_validation_code': user.password_reminder }, 'tags': ['password-reminder'], 'google_analytics_domains': ['beta.lxxl.com'], 'google_analytics_campaign': [ 'internal_password_reminder' ], 'auto_text': True, 'track_opens': True, 'track_clicks': True } ).start() output.success('reminder send', 200) except Error: pass return Controller().getResponse(True)
def set(self, environ, params): try: Controller().checkToken() #relation = Controller().getRelation() me = Controller().getUid() apikey = Controller().getApiKey() me = UserFactory.get(me) if me.uid != params['uid'] and me.level < 3: output.error('UserUnauthorized', 403) if Controller().getApiType() != 1: output.error('Not your api business', 403) # if relation != 2: # output.error( # '#ApiKeyUnauthorized : none of your business', 403) user = UserFactory.get(params['uid']) if not user: output.error('unknown user', 404) data = Controller().getRequest().json if not data: output.error('bad json format', 400) Db().get('profile').update({'uid': user.uid}, { 'datas': data, 'uid': user.uid, 'updated': datetime.datetime.utcnow() }, True) output.success('profile updated', 200) except Error: pass return Controller().getResponse(True)
def password(self, environ, params): try: Controller().checkToken() me = Controller().getUid() password = Controller().getRequest().json['password'] apikey = Controller().getApiKey() if not password: output.error('invalid format', 400) me = UserFactory.get(me) if me.uid != params['uid'] and me.level < 3: output.error('UserUnauthorized', 403) if Controller().getApiType() != 1: output.error('Not your api business', 403) user = UserFactory.get(params['uid']) if not user: output.error('unknown user', 404) #Init account on admin service try: uri = '/1.0/user/' + user.uid resp = AdminRequest().request(uri, { 'uid': user.uid, 'login': user.email, 'password': password }) except AdminError as e: output.error('Registration error : %s' % e, 500) if resp is None or int(resp.getHeader('status')) != 200: output.error('activation troubles ...', 500) output.success('password changed', 200) except Error: pass return Controller().getResponse(True)
def deactivate(self, environ, params): try: Controller().checkToken() me = Controller().getUid() apikey = Controller().getApiKey() u = UserFactory.get(me) if u.level < 3: output.error('forbidden', 403) if u.uid == params['uid']: output.error('cannot delete yourself', 403) user = UserFactory.get(params['uid']) if not user: output.error('unknown user', 404) user.activate = 0 user.deactivated = True #Init account on admin service try: uri = '/1.0/user/' + user.uid + '/deactivate' resp = AdminRequest().request(uri, { 'uid': user.uid, 'login': user.email }) except AdminError as e: output.error('Registration error : %s' % e, 500) if resp is None or int(resp.getHeader('status')) != 200: output.error('activation troubles ...', 500) Db().get('users').update({'uid': user.uid}, user) output.success('deactivated user', 200) except Error: pass return Controller().getResponse(True)
def get(self, environ, params): try: Controller().checkToken() #relation = Controller().getRelation() me = Controller().getUid() # fix privacy # if relation < 1: # output.error('#ApiKeyUnauthorized', 403) user = UserFactory.get(params['uid']) if not user: output.error('unknown user', 404) #XXX uncomment me ? # if user.activate == 0: # output.error('unactivated user', 404) result = {} Db().get('profile').ensure_index( [('uid', ASCENDING)], {'background': True}) profile = Db().get('profile').find_one({'uid': params['uid']}) if not profile: profile = {} profile['datas'] = {} result['profile'] = profile['datas'] result['email'] = user.email result['username'] = user.username result['uid'] = user.uid result['level'] = user.level if user.hasAvatar is True: result['hasAvatar'] = True else: result['hasAvatar'] = False result['friends'] = user.friends_count output.success(result, 200) except Error: pass return Controller().getResponse(True)
def create(self, environ, params): try: req = Controller().getRequest() if not req.json: output.error('invalid json', 400) a = Activity() a.saveDraft(**req.json) a.setAuthor(UserFactory.get(Controller().getUid())) a.creationDate = int(time.time()) ActivityFactory.new(a) output.success(a.toObject(), 201) except Error: pass return Controller().getResponse(True)
def reminderValidate(self, environ, params): try: datas = Controller().getRequest().json if not 'email' in datas or not 'code' in datas or not 'password' in datas: output.error('invalidate code', 400) user = UserFactory.get({'email': datas['email']}) if user is None: output.error('unknown user', 400) if not user.password_reminder: output.error('no password reminder asked', 403) if user.password_reminder != datas['code']: output.error('wrong code', 400) #Init account on admin service try: uri = '/1.0/user/' + user.uid resp = AdminRequest().request(uri, { 'uid': user.uid, 'login': user.email, 'password': datas['password'] }) except AdminError as e: output.error('Registration error : %s' % e, 500) if resp is None or int(resp.getHeader('status')) != 200: output.error('activation troubles ...', 500) user.password_reminder = None Db().get('users').update({'uid': user.uid}, user) output.success('password changed', 200) except Error: pass return Controller().getResponse(True)
def create(self, environ, params): try: datas = Controller().getRequest().json form = AccountCreateValidation.from_json(datas) if not form.validate(): output.error(form.errors) user = User() user.email = form.email.data.lower() user.username = form.username.data user.date = datetime.datetime.utcnow() #UID id = Db().get('users').increment() user.generateUid(id) #activation code user.generateActivationCode() try: user = UserFactory.new(user) except Duplicate as e: output.error({'duplicate': e.value}) #Init account on admin service try: resp = AdminRequest().request('/1.0/user/', { 'uid': user.uid, 'login': user.email.lower(), 'password': form.password.data} ) except AdminError as e: output.error('Registration error : %s' % e, 500) if resp is None or int(resp.getHeader('status')) != 201: Db().get('users').remove(user._id) output.error('registration troubles ...', 500) if 'extra' in datas: profile = datas['extra'] else: profile = {} #XXX should be done by the model Db().get('profile').update({'uid': user.uid}, { 'datas': profile, 'uid': user.uid, 'updated': datetime.datetime.utcnow() }, True) #send mail AsyncMailer( template_name='email-validation', template_content=[{ 'name': 'validation_code', 'content': user.activation_code }], global_merge_vars=[ ], message={ 'subject': 'Valider votre compte Éducation et Numérique', 'from_email': '*****@*****.**', 'from_name': 'Education & Numérique', 'headers': {}, 'to': [ { 'email': user.email, 'name': user.username } ], "global_merge_vars": [ { "name": "code", "content": user.activation_code } ], 'metadata': { 'uid': user.uid, 'email_validation_code': user.activation_code }, 'tags': ['email-validation'], 'google_analytics_domains': ['beta.lxxl.com'], 'google_analytics_campaign': [ 'internal_email_validation' ], 'auto_text': True, 'track_opens': True, 'track_clicks': True } ).start() #register user in mailchimp internal user list AsyncUserRegister( email_address=user.email, #use the invitation email and update it double_optin=False, update_existing=True, merge_vars={ 'EMAIL': user.email, 'UID': user.uid, 'USERNAME': user.username, 'FNAME': user.firstname, 'LNAME': user.lastname, 'STATUS': 'Pending activation', 'ACTCODE': user.activation_code, 'CREATIONDT': "%s" % datetime.datetime.utcnow(), 'SOURCE': 'Classic' } ).start() output.success(user.activation_code, 200) except Error: pass return Controller().getResponse(True)
def validate(self, environ, params): try: datas = Controller().getRequest().json if not 'email' in datas or not 'code' in datas: output.error('invalidate code', 400) user = UserFactory.get({'email': datas['email']}) if user is None: output.error('unknown user', 400) if user.activate == 1: output.error('already activated', 403) if user.activation_code != datas['code']: output.error('invalidate code', 400) #Init account on admin service try: uri = '/1.0/user/' + user.uid + '/activate' resp = AdminRequest().request(uri, { 'uid': user.uid, 'login': user.email }) except AdminError as e: output.error('Registration error : %s' % e, 500) if resp is None or int(resp.getHeader('status')) != 200: output.error('activation troubles ...', 500) user.activation_code = None user.activate = 1 Db().get('users').update({'uid': user.uid}, user) #send mail AsyncMailer( template_name='registered', template_content=[], global_merge_vars=[], message={ 'subject': 'Bienvenue dans la communauté des auteurs d\'Education & Numérique', 'from_email': '*****@*****.**', 'from_name': 'Education & Numérique', 'headers': {}, 'to': [ { 'email': user.email, 'name': user.username } ], 'metadata': { 'uid': user.uid }, 'tags': ['welcome'], 'google_analytics_domains': ['beta.roxee.tv'], 'google_analytics_campaign': ['internal_registered'], 'auto_text': True, 'track_opens': True, 'track_clicks': True } ).start() output.success('user activated', 200) except Error: pass return Controller().getResponse(True)