def save(self,current_user,company): """ Save form """ employee = current_user.employee_user.first() if not employee.is_manager and not employee.isCompanySuperUserOrHigher(): raise PermissionDenied() if company != employee.company and not employee.isEnsoUser(): raise PermissionDenied() password = generate_password(8) user = User.objects.create_user( username = self.cleaned_data.get('username').strip(), email = self.cleaned_data.get('email'), password = password ) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.save() return Employee.objects.create( user = user, manager = None, is_manager = self.cleaned_data.get('is_manager'), company = company, created_by = current_user, updated_by = current_user, development_plan_type = self.cleaned_data.get('development_plan_type'), language_code = self.cleaned_data.get('language_code'), plaintext_password = my_encrypt(password) )
def save(self, current_user, company): """ Save form """ employee = current_user.employee_user.first() if not employee.is_manager and not employee.isCompanySuperUserOrHigher( ): raise PermissionDenied() if company != employee.company and not employee.isEnsoUser(): raise PermissionDenied() password = generate_password(8) user = UserNxtlvl.objects.create_user( username=self.cleaned_data.get('username').strip(), email=self.cleaned_data.get('email'), password=password) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.save() return Employee.objects.create( user=user, manager=None, is_manager=self.cleaned_data.get('is_manager'), company=company, created_by=current_user, updated_by=current_user, # development_plan_type=self.cleaned_data.get('development_plan_type'), language_code=self.cleaned_data.get('language_code'), plaintext_password=my_encrypt(password))
def _sendNotification(self, user, current_user,email_text,template_code): """ Send a notification to user from current user based on template """ template = loader.get_template('mus/emails/attach_development_plan_%s.html' % template_code) if template_code=="da": subject = "NXT LVL - Udfyld forberedelsesguide" elif template_code=="en": subject = "NXT LVL - Fill out preparation guide" else: raise Exception("Unknown template: %s" % template_code) employee =user.employee_user.first() if employee.plaintext_password=='': password = generate_password(8) employee.plaintext_password = my_encrypt(password) user.set_password(password) user.save() employee.save() else: password =my_decrypt(user.employee_user.first().plaintext_password) htmlbody = template.render( Context({ 'user': user, 'text' : email_text, 'sender': current_user, 'password' : password }) ) send_mail( subject, strip_tags(htmlbody), settings.DEFAULT_FROM_MAIL, ("%s <%s>" % (user.get_full_name(),user.email),), html_message=htmlbody )
def openid_createuser(request): person = openidgae.get_current_person(request, http.HttpResponse()) email = person.get_email() res = util_externals.reponse_if_exists(email) if res is not None: return res nick = util_externals.get_nick_from_email(email) params = { 'nick': nick, 'password': util.generate_password(), 'first_name': person.get_field_value('firstname', 'none'), 'last_name': person.get_field_value('lastname', 'none'), 'fromopenid': True, 'email':email, } actor_ref = util_externals.user_create('google', params, util.display_nick(email), email) # NOTE: does not provide a flash message response = util.RedirectFlash('/', 'Welcome to %s' % util.get_metadata('SITE_NAME')) user.set_user_cookie(response, actor_ref) return response
def post(self): parser.add_argument('username', required=True, help='must input your username') parser.add_argument('password', required = True, help = 'must input your password') args = parser.parse_args() username = args.get('username') original_password = args.get('password') user = PreUcenterMember.query.filter(PreUcenterMember.username == username).first() if not user: return {'message' : 'cannot find the user, please register first!'} #encrypt method: md5(md5(password) + salt) salt = user.salt; password = generate_password(original_password, salt) if user.password == password: token = jwt.encode( {'username': user.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY']) return {'token': token.decode('UTF-8')} return 'username or password wrong!', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'}
def post(self, _id=None): ''' engineer uplaod image update engineer's image ''' file_metas = self.request.files['uploadImg'] filename, ext = _id, '' for meta in file_metas: filename = meta['filename'] content_type = meta['content_type'] if not _id: _id = self._gen_image_id_(filename, content_type, util.generate_password(8)) else: # previous data has been existed, delete previous first msg.delete_file(_id) msg.create_file(meta['body'], _id=_id, filename=filename, content_type=content_type) break if filename: self.render_json_response(url='/fs/' + _id, **self.OK) else: raise HTTPError(400)
def post(self): file_metas = self.request.files['upfile'] filename, ext = '', '' for meta in file_metas: filename = meta['filename'] content_type = meta['content_type'] now = _now() mask = util.generate_password(8) md5 = util.md5(filename, content_type, now, mask) _id = md5.hexdigest().lower() msg.create_file(meta['body'], _id=_id, filename=filename, content_type=content_type) break if filename and _id: self.render_json_response(url='/fs/' + _id, title=filename, type=content_type, state='SUCCESS', **self.OK) else: raise HTTPError(400)
def post(self): parser.add_argument('username', required=True, help='username cannot be empty') parser.add_argument('password', required=True, help='password cannot be empty') parser.add_argument('email', required=True, help='password cannot be empty') args = parser.parse_args() username = args.get('username') orginal_password = args.get('password') email = args.get('email') regip = request.remote_addr regdate = int(time.time()) user = PreUcenterMember.query.filter( PreUcenterMember.username == username).first() if user: return { 'message': 'username has already been registered, try another one' } if len(orginal_password) < 6: return {'message': 'password must be no less than 6 characters'} if not validate_email(email): return {'message': 'email format is invalid'} # generate 6 digit Hexadecimal number as salt salt = '' for _ in range(1, 7): salt = salt + format(random.randint(0, 15), 'x') password = generate_password(orginal_password, salt) new_user = PreUcenterMember(username=username, password=password, email=email, regip=regip, regdate=regdate, salt=salt) db.session.add(new_user) #although pre_common_member is not used to login, this schema need to be updated. Otherwise, an account activation is prompted #when loging in the webiste using browser. new_user_common = PreCommonMember(username=username, password=password, email=email, regdate=regdate) db.session.add(new_user_common) db.session.commit() return { 'message': '%s is registered successfully. You can use it to sign up now.' % username }
def twitter_user_create(request): twitter_user, token = util_externals.twitter_user() if not twitter_user: c = template.RequestContext(request, locals()) t = loader.get_template('poboxopenid/templates/twitter_login.html') return http.HttpResponse(t.render(c)) res = util_externals.reponse_if_exists(twitter_user.id, 'twitter') if res is not None: return res nick = util_externals.get_nick_from_email(twitter_user.screen_name) params = { 'nick': nick, 'password': util.generate_password(), 'first_name': twitter_user.name, 'last_name': '', 'fromopenid': True, 'email':None, } actor_ref = util_externals.user_create('twitter', params, twitter_user.screen_name, str(twitter_user.id), 'http://twitter.com/%s'%twitter_user.screen_name) logging.info("Storing twitter_access_token after create a user") actor_ref.extra['twitter_access_token'] = token actor_ref.put() response = util.RedirectFlash('/', 'Welcome to P.O.BoxPress') user.set_user_cookie(response, actor_ref) return response #@decorator_from_middleware(FacebookMiddleware) #@facebook.require_login('/facebook/signin', False) #def facebook_processuser(request): # c = template.RequestContext(request, locals()) # t = loader.get_template('poboxopenid/templates/facebook_login.html') # return http.HttpResponse(t.render(c)) #@decorator_from_middleware(FacebookMiddleware) #@facebook.require_login('/facebook/signin', False) #def facebook_canvas(request): # values = request.facebook.users.getInfo([request.facebook.uid], ['first_name', 'is_app_user', 'has_added_app'])[0] # # name, is_app_user, has_added_app = values['first_name'], values['is_app_user'], values['has_added_app'] # # if has_added_app == '0': # return request.facebook.redirect(request.facebook.get_add_url()) # # c = template.RequestContext(request, locals()) # t = loader.get_template('poboxopenid/templates/canvas.fbml') # return http.HttpResponse(t.render(c))
def save(self, company, request): """ Save form """ for data in self.cleaned_data['employee_file']: manager_email = Employee.objects.get( user__email=data.get('manager')).id manager = Employee.objects.get(pk=manager_email) if not self.employee.isEnsoUser(): if not self.employee.is_manager and not self.employee.isCompanySuperUserOrHigher( ): logUnauthorizedAccess( "User tried to EmployeeForm. Accesscheck: 1", self.request) raise PermissionDenied() if self.cleaned_data.get( 'is_manager' ) and not self.employee.isCompanySuperUserOrHigher(): logUnauthorizedAccess( "User tried to EmployeeForm. Accesscheck: 2", self.request) raise PermissionDenied() current_user = get_user_model().objects.get(pk=request.user.pk) password = generate_password(8) user_model = get_user_model() users = user_model.objects.filter(email=data.get('email')).all() # if users: # raise SuspiciousOperation("A user with the given username/email already exists", 400) user = user_model.objects.create_user(username=data.get('email'), email=data.get('email'), password=password) user.first_name = data.get('first_name') user.last_name = data.get('last_name') user.save() Employee.objects.create( user=user, manager=manager, is_manager=False if data.get('is_manager') == 'false' else True, company=self.employee.company, created_by=current_user, updated_by=current_user, # development_plan_type=self.cleaned_data.get('development_plan_type'), language_code=data.get('language_code') # plaintext_password=my_encrypt(password) ) email_subject = 'Next level' email_body = 'Created a new user: {}, your email: {}, your password: {}.' \ 'To register please go to http://nxtlvl-dev.chisw.us/login' \ .format(user.username, user.email, password) sender = settings.DEFAULT_FROM_EMAIL recipients = ['{}'.format(user.email)] send_emails.delay(recipients, email_subject, email_body, sender)
def save(self): employee = Employee.objects.get( user__email__exact=self.cleaned_data['email']) # mail_from = '*****@*****.**' # subject = _("NXT LVL: new password") password = generate_password(8) print password employee.user.set_password(password) employee.user.save() email_subject = 'Next level' email_body = 'NXT LVL: new password: {}'.format(password) sender = settings.DEFAULT_FROM_EMAIL recipients = ['{}'.format(employee.user.email)] send_emails.delay(recipients, email_subject, email_body, sender)
def save(self): employee = Employee.objects.get(user__email__exact=self.cleaned_data['email']) subject = _("NXT LVL: new password") password = generate_password(8) employee.user.set_password(password) employee.user.save() template = loader.get_template('mus/emails/reset_password_%s.html' % employee.language_code) htmlbody = template.render( Context({ 'user': employee.user, 'access_code': employee.getAccessCode(), 'newpassword' : password }) ) send_mail( subject, strip_tags(htmlbody), settings.DEFAULT_FROM_MAIL, (employee.user.email,), html_message=htmlbody )
def save(self): """ Save form and send welcome mail (currently disabled) """ employee = Employee.objects.get(user__pk = self.user.pk) if not employee.isEnsoUser(): if not employee.is_manager and not employee.isCompanySuperUserOrHigher(): logUnauthorizedAccess("User tried to EmployeeForm. Accesscheck: 1", self.request) raise PermissionDenied() if self.cleaned_data.get('is_manager') and not employee.isCompanySuperUserOrHigher(): logUnauthorizedAccess("User tried to EmployeeForm. Accesscheck: 2", self.request) raise PermissionDenied() if self.cleaned_data.get('company') != employee.company: logUnauthorizedAccess("User tried to EmployeeForm. Accesscheck: 3", self.request) raise PermissionDenied() password = generate_password(8) user = User.objects.create_user( username = self.cleaned_data.get('user_name'), email = self.cleaned_data.get('email'), password = password ) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.save() manager = self.cleaned_data.get('manager') Employee.objects.create( user = user, manager = manager, is_manager = self.cleaned_data.get('is_manager'), company = self.cleaned_data.get('company'), created_by = self.user, updated_by = self.user, development_plan_type = self.cleaned_data.get('development_plan_type'), language_code = self.cleaned_data.get('language_code'), plaintext_password = my_encrypt(password) )
def save(self): """ Save form and send welcome mail (currently disabled) """ employee = Employee.objects.get(user__pk=self.user.pk) ###!!!!!!!!!! data = self.data employee_manager = Employee.objects.get(pk=data['manager']) man_list = [] from views import found_all_managers manager_list = list( Employee.objects.filter(manager=employee, is_manager=True)) if employee.is_manager == True: manager_list.append(employee) if len(manager_list) > 0: result_list = manager_list all_managers_list = found_all_managers(manager_list, result_list) else: raise forms.ValidationError( _('"error": "this employee have not any manager"')) employees = list() for manager in all_managers_list: manager_dict = model_to_dict(manager) for k in ['first_name', 'last_name', 'email']: manager_dict[k] = getattr(manager.user, k) manager_dict['photo'] = manager.photo.url if manager.photo else '' employees.append(manager_dict) for i in employees: man_list.append(i['email']) man_list.append(employee.user.email) if employee_manager.user.email not in man_list: raise forms.ValidationError( _('you can not given manager with id={}, changed manager'. format(data['manager']))) # if not employee.isEnsoUser(): # if not employee.is_manager and not employee.isCompanySuperUserOrHigher(): # logUnauthorizedAccess("User tried to EmployeeForm. Accesscheck: 1", self.request) # raise PermissionDenied() # if self.cleaned_data.get('is_manager') and not employee.isCompanySuperUserOrHigher()\ # and not employee.id == employee_parent.manager_id: # logUnauthorizedAccess("User tried to EmployeeForm. Accesscheck: 2", self.request) # raise PermissionDenied() # if self.cleaned_data.get('company') != employee.company: # logUnauthorizedAccess("User tried to EmployeeForm. Accesscheck: 3", self.request) # raise PermissionDenied() password = generate_password(8) user_model = get_user_model() users = user_model.objects.filter(email=data.get('email')).all() if users: raise SuspiciousOperation( "A user with the given username/email already exists", 400) user = user_model.objects.create_user( # username=self.cleaned_data.get('user_name'), username=data.get('email'), email=data.get('email'), password=password) # user.username = self.cleaned_data.get('first_name') user.first_name = data.get('first_name') user.last_name = data.get('last_name') user.save() id = int(data.get('manager')) manager = Employee.objects.get(id=id) Employee.objects.create( user=user, manager=manager, is_manager=data.get('is_manager'), company=manager.company, created_by=self.user, updated_by=self.user, # development_plan_type=self.cleaned_data.get('development_plan_type'), language_code=data.get('language_code'), # plaintext_password=my_encrypt(password) title=data.get('title'), ) email_subject = 'Next level' email_body = 'Created a new user: {}, your email: {}, your password: {}.' \ 'To register please go to http://nxtlvl-dev.chisw.us/login'\ .format(user.username, user.email, password) sender = settings.DEFAULT_FROM_EMAIL recipients = ['{}'.format(user.email)] send_emails.delay(recipients, email_subject, email_body, sender)
def join_join(request): if request.user: raise exception.AlreadyLoggedInException() redirect_to = request.REQUEST.get('redirect_to', '/') account_types = api.get_config_values(api.ROOT, 'account_type') # get the submitted vars nick = request.REQUEST.get('nick', ''); first_name = request.REQUEST.get('first_name', ''); last_name = request.REQUEST.get('last_name', ''); email = request.REQUEST.get('email', ''); password = request.REQUEST.get('password', ''); confirm = request.REQUEST.get('confirm', ''); hide = request.REQUEST.get('hide', ''); country_tag = request.REQUEST.get('country_tag', '') if request.POST: try: # TODO validate params = util.query_dict_to_keywords(request.POST) if hide: params['privacy'] = 2 # XXX: Check if the data come from a openid account # @author: [email protected] fromopenid = request.POST.get('fromopenid', False) and True if fromopenid: try: person = openidgae.get_current_person(request, http.HttpResponse()) except: raise exception.ServiceError email = person.get_email() if email == params['email']: params['password'] = util.generate_password() else: raise exception.ServiceError # ENDXXX validate.email(email) if not mail.is_allowed_to_send_email_to(email): raise exception.ValidationError("Cannot send email to that address") # TODO start transaction if api.actor_lookup_email(api.ROOT, email): raise exception.ValidationError( 'That email address is already associated with a member.') actor_ref = api.user_create(api.ROOT, **params) actor_ref.access_level = "delete" api.post(actor_ref, nick=actor_ref.nick, message='Joined %s!' % (util.get_metadata('SITE_NAME'))) if fromopenid: api.email_associate(api.ROOT, actor_ref.nick, email) else: # send off email confirmation api.activation_request_email(actor_ref, actor_ref.nick, email) logging.info('setting firsttime_%s from register page' % actor_ref.nick) memcache.client.set('firsttime_%s' % nick, True) # TODO end transaction welcome_url = util.qsa('/', {'redirect_to': redirect_to}) # NOTE: does not provide a flash message response = http.HttpResponseRedirect(welcome_url) user.set_user_cookie(response, actor_ref) return response except: exception.handle_exception(request) # for legal section legal_component = component.include('legal', 'dummy_legal') legal_html = legal_component.embed_join() # for sidebar sidebar_green_top = True area = "join" c = template.RequestContext(request, locals()) t = loader.get_template('join/templates/join.html') return http.HttpResponse(t.render(c))