Esempio n. 1
0
 def _check_note(self, note):
     if not note.entry_date:
         self.alert(
             'A note record is missing an entry_date value (%s).' %
             note.record_id)
     if not note.original_creation_date:
         self.alert(
             'A note record is missing an original_creation_date value (%s).'
             % note.record_id)
     if not note.person_record_id:
         self.alert(
             'A note record is missing a person_record_id value (%s).' %
             note.record_id)
     if (note.author_email and not utils.validate_email(note.author_email)):
         self.alert(
             'A note record has an invalid author_email value (%s).' %
             note.record_id)
     if (note.email_of_found_person and
             not utils.validate_email(note.email_of_found_person)):
         self.alert(
             'A note record has an invalid email_of_found_person value (%s).'
             % note.record_id)
     if not model.Person.get(self.env.repo, note.person_record_id):
         self.alert(
             'A note record\'s associated person record is missing (%s).' %
             note.record_id)
Esempio n. 2
0
def share_command():
    if "-l" in sys.argv:
        ss = get_spreadsheet()
        print_permissions(ss)
    elif "-a" in sys.argv:
        email = get_argument(sys.argv, "-a")
        if validate_email(email):
            try:
                display_loading_message("Adding permission", "Permission added")
                ss = get_spreadsheet()
                share_spreadsheet(ss, email)
                hide_loading_message_with_error(False)
            except Exception:
                hide_loading_message_with_error(True)
        else:
            write_error("Invalid email: " + email)
    elif "-d" in sys.argv:
        email = get_argument(sys.argv, "-d")
        if validate_email(email):
            try:
                display_loading_message("Removing permission", "Permission removed")
                ss = get_spreadsheet()
                ss.remove_permissions(email)
                hide_loading_message_with_error(False)
            except Exception:
                hide_loading_message_with_error(True)
        else:
            write_error("Invalid email: " + email)
Esempio n. 3
0
 def _check_note(self, note):
     if not note.entry_date:
         self.alert('A note record is missing an entry_date value (%s).' %
                    note.record_id)
     if not note.original_creation_date:
         self.alert(
             'A note record is missing an original_creation_date value (%s).'
             % note.record_id)
     if not note.person_record_id:
         self.alert(
             'A note record is missing a person_record_id value (%s).' %
             note.record_id)
     if (note.author_email and not utils.validate_email(note.author_email)):
         self.alert(
             'A note record has an invalid author_email value (%s).' %
             note.record_id)
     if (note.email_of_found_person
             and not utils.validate_email(note.email_of_found_person)):
         self.alert(
             'A note record has an invalid email_of_found_person value (%s).'
             % note.record_id)
     if not model.Person.get(self.env.repo, note.person_record_id):
         self.alert(
             'A note record\'s associated person record is missing (%s).' %
             note.record_id)
Esempio n. 4
0
def share_document(request, id):
    """View for managing sharing of a document"""
    doc = get_object_or_404(Document, id=id)
    if request.user != doc.owner:
        raise Http404
    ctx = copy.copy(default_ctx)
    ctx['success'] = False
    if request.method == 'POST':
        visibility_form = VisibilityForm(request.POST, instance=doc)
        emails = request.POST.getlist('conemails', [])
        if not isinstance(emails, list):
            emails = [emails]
        emails_pass = True
        emailsv = []
        # remove owner email, empty or errorneous emails
        for a in emails:
            if doc.owner.email == a or len(a) <= 0 or not validate_email(a):
                continue
            emailsv.append(a)
        if visibility_form.is_valid() and emails_pass:
            doc.visibility = visibility_form.cleaned_data['visibility']
            doc.contributors = User.objects.filter(email__in=emailsv)
            doc.save()
            ctx['success'] = True
    else:
        visibility_form = VisibilityForm(instance=doc)
    conemails = list(doc.contributors.values_list("email", flat=True))
    # this shouldn't throw an exception
    ctx['conemails'] = json.dumps([{"conemails":x} for x in conemails])

    ctx['doc'] = doc
    ctx['visibility_form'] = visibility_form
    return render_to_response('share_document.html', ctx, RequestContext(request))
Esempio n. 5
0
    def on_post(self, req, resp):
        try:
            raw_json = req.stream.read().decode("utf-8")
        except Exception as ex:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', ex.args)

        try:
            result_json = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect.')

        # inner request object
        reqo = {}
        for item in result_json:
            reqo[item['name']] = item['value']

        email = reqo['email']

        # inner response object
        reso = {}
        if not validate_email(email):
            reso['is_e'] = True
            reso['e'] = 'Email ' + email + ' is invalid.'
        else:
            reso['is_e'] = False
            reso['username'] = extract_username(email)
            reso['email'] = email

            search_task.delay(reqo)

        resp.body = json.dumps(reso)
        resp.status = falcon.HTTP_200
Esempio n. 6
0
    def post(self):
        raw_username = self.request.get("username")
        raw_password = self.request.get("password")
        raw_email = self.request.get("email")
        raw_verify = self.request.get("verify")

        username = utils.validate_username(raw_username)
        password = utils.validate_password(raw_password)
        email = utils.validate_email(raw_email)

        if not (username and password and raw_password==raw_verify and email):
            form_values = {'username':raw_username, 'email':raw_email}
            if not username:
                form_values['username_error'] = 'Invalid username!'
                form_values['isUserErrorOrSuccess'] = 'error'
            if not password:
                form_values['password_error'] = 'Invalid password!'
                form_values['isPassErrorOrSuccess'] = 'error'
            if raw_password!=raw_verify:
                form_values['verify_error'] = "Ooops! Doesn't match to the password above"
                form_values['isVerifyErrorOrSuccess'] = 'error'
            if not email:
                form_values['email_error'] = "Invalid email address!"
                form_values['isEmailErrorOrSuccess'] = 'error'
            self.render(signup_template, **form_values)
        else:
            self.redirect("welcome?user=%s" % str(raw_username))
Esempio n. 7
0
    def forgot_password(self, that=None):
        try:
            response = {
                "success": False,
                "message": "Something went wrong",
                "data": []
            }
            form = cgi.FieldStorage(fp=that.rfile,
                                    headers=that.headers,
                                    environ={
                                        'REQUEST_METHOD':
                                        'POST',
                                        'CONTENT_TYPE':
                                        that.headers['Content-Type'],
                                    })

            form_keys = list(form.keys())
            email = form['email'].value

            if not validate_email(email):
                response['message'] = "Email is not a valid"
                return response

            data = {}
            data['email'] = email

            response['success'] = True
            response['message'] = "data is valid"
            response['data'] = [data]

        except Exception as e:
            response = response
        return response
Esempio n. 8
0
def send_reset_email(request, schema, **kwargs):
    email = schema.email
    api   = globalMongoStampedAPI()
    
    if not utils.validate_email(email):
        msg = "Invalid format for email address"
        logs.warning(msg)
        raise StampedInvalidEmailError("Invalid email address")
    
    # verify account exists
    try:
        user = stampedAPIProxy.checkAccount(email)
        
        if user is None:
            raise
    except Exception:
        utils.printException()
        logs.error("ERROR: invalid email '%s'" % email)
        
        ### TODO: Display appropriate error message
        errorMsg = 'No account information was found for that email address.'
        raise StampedHTTPError(404, msg="Email address not found", kind='invalid_input')
    
    account = stampedAPIProxy.getAccount(user['user_id'])
    auth_service = account['auth_service']
    
    if auth_service != 'stamped':
        raise StampedInputError("Account password not managed by Stamped for user '%s' (primary account service is '%s')" % (account['screen_name'], auth_service))
    
    # send email
    logs.info("sending email to '%s' (user: '******')" % (email, user['screen_name']))
    result = g_stamped_auth.forgotPassword(email)
    
    return transform_output(result)
Esempio n. 9
0
 def post(self, request, *args, **kwargs):
     """
     :param request: here is post request por set password
     :return: in this function we take email from user and send toaken for verification
     """
     try:
         if not 'email' in request.data:
             raise KeyError('email is missing')
         email = request.data['email']
         print(email)
         if email == "":
             raise KeyError('email field not be blank')
         if not validate_email(email):
             raise ValueError
         user = User.objects.get(email=email)
         if user:
             payload = {
                 'username': user.username,
                 'email': user.email,
             }
             token = Jwt().register_token(payload)
             long_url = reverse('reset_password', args=[token])
             short_url = get_short_url(long_url)  # Url object
             message = render_to_string(
                 'users/email_template.html', {
                     'name': user.username,
                     'domain': get_current_site(request).domain,
                     'url': short_url.short_id
                 })
             recipient_list = [
                 user.email,
             ]
             email_event.emit("reset_password_event", message,
                              recipient_list)
             smd = Smd_Response(
                 True,
                 'you"re email is verified for reset password check you"re email',
                 status_code=200)
             return smd
         else:
             smd = Smd_Response(False,
                                'you are not valid user register first', [])
             logger.warning(
                 'not valid user warning from users.views.Reset_password_api'
             )
     except ObjectDoesNotExist as e:
         logger.warning('email not registered' + str(e))
         smd = Smd_Response(False, 'this email id not registered', [])
     except ValueError as e:
         smd = Smd_Response(False, 'please provide valid email address', [])
         logger.warning('not valid email address' + str(e))
     except KeyError as error:
         smd = Smd_Response(False, str(error), [])
         logger.warning('input is blank ' + str(error))
     except Exception as e:
         logger.warning('something is wrong ' + str(e))
         smd = Smd_Response()
     return smd
Esempio n. 10
0
def passwordForgot(request):

    errorMsg = 'An error occurred. Please try again.'

    try:
        # Check if a form exists with data
        if request.method == 'POST':
            # User submitted the form
            data = request.POST

            # Validate email address
            email = str(data['forgotemail']).lower().strip()
            if not utils.validate_email(email):
                msg = "Invalid format for email address"
                logs.warning(msg)
                raise StampedInvalidEmailError("Invalid email address")
            
            # Verify account exists
            try:
                user = stampedAPI.checkAccount(email)
            except:
                ### TODO: Display appropriate error message
                errorMsg = 'No account information was found for that email address.'
                raise StampedHTTPError(404, msg="Email address not found", kind='invalid_input')

            # Send email
            stampedAuth.forgotPassword(email)

            # Return success
            response = HttpResponseRedirect('/settings/password/sent')

        else:
            # Display 'submit email' form
            response = render_to_response('password-forgot.html', None)

        return response

    except Exception as e:
        logs.begin(
            addLog=stampedAPI._logsDB.addLog, 
            saveLog=stampedAPI._logsDB.saveLog,
            saveStat=stampedAPI._statsDB.addStat,
            requestData=request,
        )
        logs.request(request)
        logs.warning("500 Error: %s" % e)
        logs.error(500)
        logs.save()

        return render_to_response('password-forgot.html', {'error': errorMsg})

    return True
Esempio n. 11
0
 def _check_person(self, person):
     if not person.entry_date:
         self.alert('A person record is missing an entry_date value (%s).' %
                    person.record_id)
     if not person.original_creation_date:
         self.alert(
             'A person record is missing an original_creation_date value'
             '(%s).' % person.record_id)
     if (person.author_email
             and not utils.validate_email(person.author_email)):
         self.alert(
             'A person record has an invalid author_email value (%s).' %
             person.record_id)
Esempio n. 12
0
 def _check_person(self, person):
     if not person.entry_date:
         self.alert(
             'A person record is missing an entry_date value (%s).'
             % person.record_id)
     if not person.original_creation_date:
         self.alert(
             'A person record is missing an original_creation_date value'
             '(%s).' % person.record_id)
     if (person.author_email and
             not utils.validate_email(person.author_email)):
         self.alert(
             'A person record has an invalid author_email value (%s).'
             % person.record_id)
Esempio n. 13
0
    def post(self, request):
        try:
            data = json.loads(request.body)

            email = data['email']
            password = data['password']
            account = data.get('account')
            mobile = data.get('mobile')

            if not validate_length(data):
                return JsonResponse({'MESSAGE': 'DATA_TOO_LONG'}, status=400)

            if not validate_email(email):
                return JsonResponse({'MESSAGE': 'INVALID_EMAIL'}, status=400)

            if User.objects.filter(email=email).exists():
                return JsonResponse({'MESSAGE': 'EMAIL_ALREADY_EXISTS'},
                                    status=409)

            if not validate_password(password):
                return JsonResponse({'MESSAGE': 'INVALID_PASSWORD'},
                                    status=400)

            if account and User.objects.filter(account=account).exists():
                return JsonResponse({'MESSAGE': 'ACCOUNT_ALREADY_EXISTS'},
                                    status=409)

            if mobile and not validate_mobile(mobile):
                return JsonResponse({'MESSAGE': 'INVALID_MOBILE'}, status=400)

            if mobile and User.objects.filter(mobile=mobile).exists():
                return JsonResponse({'MESSAGE': 'MOBILE_ALREADY_EXISTS'},
                                    status=409)

            User.objects.create(email=email,
                                password=bcrypt.hashpw(
                                    password.encode('utf-8'),
                                    bcrypt.gensalt()).decode('utf-8'),
                                account=account,
                                mobile=mobile)

        except json.decoder.JSONDecodeError:
            return JsonResponse({'MESSAGE': 'REQUEST_WITHOUT_DATA'},
                                status=400)

        except KeyError:
            return JsonResponse({'MESSAGE': 'KEY_ERROR'}, status=400)

        return JsonResponse({'MESSAGE': 'SUCCESS'}, status=201)
Esempio n. 14
0
    def post(self):
        """Post a note in person's record view page"""
        if not self.params.text:
            return self.error(
                400, _('Message is required. Please go back and try again.'))

        if not self.params.author_name:
            return self.error(
                400,
                _('Your name is required in the "About you" section.  '
                  'Please go back and try again.'))

        if (self.params.status == 'is_note_author'
                and not self.params.author_made_contact):
            return self.error(
                400,
                _('Please check that you have been in contact with '
                  'the person after the disaster, or change the '
                  '"Status of this person" field.'))
        if (self.params.status == 'believed_dead'
                and not self.config.allow_believed_dead_via_ui):
            return self.error(
                400,
                _('Not authorized to post notes with the status '
                  '"believed_dead".'))

        if (self.params.author_email
                and not utils.validate_email(self.params.author_email)):
            return self.error(
                400, _('The email address you entered appears to be invalid.'))

        person = Person.get(self.repo, self.params.id)
        if person.notes_disabled:
            return self.error(
                400,
                _('The author has disabled status updates '
                  'on this record.'))

        # If a photo was uploaded, create and store a new Photo entry and get
        # the URL where it's served; otherwise, use the note_photo_url provided.
        photo, photo_url = (None, self.params.note_photo_url)
        if self.params.note_photo is not None:
            try:
                photo, photo_url = create_photo(self.params.note_photo, self)
            except PhotoError, e:
                return self.error(400, e.message)
            photo.put()
Esempio n. 15
0
    def register(self, that=None):
        try:
            response = {
                "success": False,
                "message": "something went wrong",
            }
            form = cgi.FieldStorage(fp=that.rfile,
                                    headers=that.headers,
                                    environ={
                                        'REQUEST_METHOD':
                                        'POST',
                                        'CONTENT_TYPE':
                                        that.headers['Content-Type'],
                                    })
            form_keys = list(form.keys())
            username = form['username'].value
            email = form['email'].value
            password = form['password'].value

            if len(username) == 0:
                response['message'] = "username cannot be empty"
                raise ValueError

            if not validate_email(email):
                response['message'] = "Email is not a valid"
                return response

            if len(password) == 0:
                response['message'] = "password not be empty"
                raise ValueError

            data = {}
            data['username'], data['email'], data[
                'password'] = username, email, password

            # updating response
            response['success'], response['message'], response[
                'data'] = True, "data is valid", [data]

        except ValueError:
            response = response

        except Exception as e:
            response = response
        return response
Esempio n. 16
0
    def post(self):
        if not (self.auth and self.auth.subscribe_permission):
            return self.error(403, 'Missing or invalid authorization key')

        if not validate_email(self.params.subscribe_email):
            return self.error(400, 'Invalid email address')

        person = model.Person.get(self.repo, self.params.id)
        if not person:
            return self.error(400, 'Invalid person_record_id')

        subscription = subscribe.subscribe_to(self, self.repo, person,
                                              self.params.subscribe_email,
                                              self.env.lang)
        utils.log_api_action(self, ApiActionLog.SUBSCRIBE)
        if not subscription:
            return self.info(200, 'Already subscribed')
        return self.info(200, 'Successfully subscribed')
Esempio n. 17
0
    def post(self):
        if not (self.auth and self.auth.subscribe_permission):
            return self.error(403, 'Missing or invalid authorization key')

        if not validate_email(self.params.subscribe_email):
            return self.error(400, 'Invalid email address')

        person = model.Person.get(self.repo, self.params.id)
        if not person:
            return self.error(400, 'Invalid person_record_id')

        subscription = subscribe.subscribe_to(self, self.repo, person,
                                              self.params.subscribe_email,
                                              self.env.lang)
        utils.log_api_action(self, ApiActionLog.SUBSCRIBE)
        if not subscription:
            return self.info(200, 'Already subscribed')
        return self.info(200, 'Successfully subscribed')
Esempio n. 18
0
def register():
    credentials = request.get_json(force=True)
    email = credentials['email']
    if not validate_email(email):  
        return jsonify({"code": 2, "token": None})
    app_id = credentials.pop('app_id') 
    if db.session.query(UserAccount).filter_by(email=email).first():
        return jsonify({"code": 1, "token": None})
    else:
        if db.session.query(Application).filter_by(id=app_id).first():
            token = generate_token()
            user = UserAccount(**credentials)
            db.session.add(user)
            db.session.commit()
            db.session.add(UserApplication(user_id=user.id, application_id=app_id, token=token))
            db.session.commit()
            return jsonify({"code": 0, "token": token})
        else:
            return jsonify({"code": 2, "token": None})
Esempio n. 19
0
    def post(self):
        """Post a note in person's record view page"""
        if not self.params.text:
            return self.error(
                400, _('Message is required. Please go back and try again.'))

        if not self.params.author_name:
            return self.error(
                400, _('Your name is required in the "About you" section.  '
                       'Please go back and try again.'))

        if (self.params.status == 'is_note_author' and
            not self.params.author_made_contact):
            return self.error(
                400, _('Please check that you have been in contact with '
                       'the person after the disaster, or change the '
                       '"Status of this person" field.'))
        if (self.params.status == 'believed_dead' and
            not self.config.allow_believed_dead_via_ui):
            return self.error(
                400, _('Not authorized to post notes with the status '
                       '"believed_dead".'))

        if (self.params.author_email and
            not utils.validate_email(self.params.author_email)):
            return self.error(400, _(
                'The email address you entered appears to be invalid.'))

        person = Person.get(self.repo, self.params.id)
        if person.notes_disabled:
            return self.error(
                400, _('The author has disabled status updates '
                       'on this record.'))

        # If a photo was uploaded, create and store a new Photo entry and get
        # the URL where it's served; otherwise, use the note_photo_url provided.
        photo, photo_url = (None, self.params.note_photo_url)
        if self.params.note_photo is not None:
            try:
                photo, photo_url = create_photo(self.params.note_photo, self)
            except PhotoError, e:
                return self.error(400, e.message)
            photo.put()
Esempio n. 20
0
def sign_up(request):
    if request.POST:

        email = request.POST['email']
        username = request.POST['username']
        password = request.POST['password']
        password_confirm = request.POST['password_confirm']

        msg = ''
        if not utils.validate_email(email):
            msg = u'邮箱格式不正确'
            return JsonResponse({'success': False, 'msg': msg})

        if password != password_confirm:
            msg = u'两次密码输入不一致'
            return JsonResponse({'success': False, 'msg': msg})

        if db_utils.email_registered(email):
            msg = u'该邮箱已被注册'
            return JsonResponse({'success': False, 'msg': msg})

        if db_utils.name_used(username):
            msg = u'该昵称已被使用'
            return JsonResponse({'success': False, 'msg': msg})

        try:
            db_utils.add_user(email, username, password)
            msg = u'注册成功'
        except Exception as e:
            msg = u'注册失败'

        user = authenticate(username=email, password=password)
        if user and user.is_active:
            login(request, user)

        return JsonResponse({'success': True, 'msg': msg, 'url': '/'})
    else:
        return render(request, "sign_up.html")
Esempio n. 21
0
    def verifyUserCredentials(self, clientId, userIdentifier, password):
        # Login via email
        if utils.validate_email(userIdentifier):
            account = self._accountDB.getAccountByEmail(userIdentifier)
        # Login via screen name
        elif utils.validate_screen_name(userIdentifier):
            account = self._accountDB.getAccountByScreenName(userIdentifier)
        else:
            raise StampedInvalidCredentialsError("Account not found: %s" % userIdentifier)

        if account.auth_service != 'stamped':
            raise StampedWrongAuthServiceError("Attempting a stamped login for an account that doesn't use stamped for auth")

        if not auth.comparePasswordToStored(password, account.password):
            raise StampedInvalidCredentialsError("Invalid password for user: %s" % userIdentifier)

        logs.info("Login successful")

        """
        IMPORTANT!!!!!

        Right now we're returning a refresh token upon login. This will
        have to change ultimately, but it's an okay assumption for now
        that every login will be from the iPhone. Once that changes we may
        have to modify this.

        Also, we'll ultimately need a way to deprecate unused refresh
        tokens. Not sure how we'll implement that yet....
        """

        ### Generate Refresh Token & Access Token
        token = self.addRefreshToken(clientId, account.user_id)

        logs.info("Token created")

        return account, token
Esempio n. 22
0
def init_app():
    print("Starting servy init process")
    print("............................")
    credentials_path = get_credentials_path()
    while True:
        default_spreadsheet = input("Insert the spreadsheets name\n")
        if default_spreadsheet:
            try:
                append_default_spreadsheet(credentials_path, default_spreadsheet)
                break
            except FileNotFoundError:
                write_error("\n'credentials.json' does not exists\n")
                print("Enter/Paste the downloaded content. Ctrl-D to save it.")
                try:
                    credentials_content = []
                    while True:
                        try:
                            line = input()
                        except EOFError:
                            break
                        credentials_content.append(line)

                    with open(credentials_path, "w+") as f:
                        for line in credentials_content:
                            f.write(line + "\n")

                    append_default_spreadsheet(credentials_path, default_spreadsheet)
                    break
                except PermissionError:
                    write_error("Permission error\n`servy init` should be run using root permissions\n")
                    exit()
                except Exception as e:
                    write_error("An error occured while saving credentials\n")
                    exit()
                    
    ss = get_spreadsheet()
    if ss and ss.sheet1:
        resume_ss = input(
            "A spreadsheet with this name already exists. Do you want to use it? Y/N\n")
        if resume_ss == "Y":
            print("Spreadsheet in use: " + default_spreadsheet)
            print("The following users has read permission to this file")
            print_permissions(ss)
            return

    print("Insert the email you want to have access to the spreadsheet")
    while True:
        email = input("Insert email: ")
        if email:
            if not validate_email(email):
                write_error("Invalid email")
            else:
                break

    display_loading_message("Creating spreadsheet " + default_spreadsheet, "Created spreadsheet " + default_spreadsheet)
    try:
        if ss:
            delete_spreadsheet(ss)
        ws = create_spreadsheet(email)
        init_spreadsheet(ws)
        hide_loading_message_with_error(False)
    except:
        hide_loading_message_with_error(True)
Esempio n. 23
0
    def forgotPassword(self, email):
        email = str(email).lower().strip()
        if not utils.validate_email(email):
            msg = "Invalid format for email address"
            logs.warning(msg)
            raise StampedInputError(msg)
        
        # Verify user exists
        account = self._accountDB.getAccountByEmail(email)
        if not account or not account.user_id:
            msg = "User does not exist"
            logs.warning(msg)
            raise StampedInputError(msg)
        
        attempt = 1
        max_attempts = 5
        expire = 1800    # 30 minutes
        
        while True:
            try:
                rightNow = datetime.utcnow()

                resetToken = PasswordResetToken()
                resetToken.token_id = auth.generateToken(36)
                resetToken.user_id = account.user_id
                resetToken.expires = rightNow + timedelta(seconds=expire)
                
                timestamp = BasicTimestamp()
                timestamp.created = rightNow
                resetToken.timestamp = timestamp
                
                self._passwordResetDB.addResetToken(resetToken)
                break
            except Exception:
                if attempt >= max_attempts:
                    ## Add logging
                    raise 
                attempt += 1

        # TODO: switch this back to https after resolving the issue where assets 
        # aren't loaded over SSL
        url = 'http://www.stamped.com/pw/%s' % resetToken.token_id
        prettyurl = 'http://stamped.com/pw/%s' % resetToken.token_id
        
        # Email user
        msg = {}
        msg['to'] = email
        msg['from'] = 'Stamped <*****@*****.**>'
        msg['subject'] = 'Stamped: Forgot Password'
        
        try:
            base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            path = os.path.join(base, 'alerts', 'templates', 'email_password_forgot.html.j2')
            template = open(path, 'r')
        except Exception:
            ### TODO: Add error logging?
            raise
        
        params = {'url': url, 'prettyurl': prettyurl}
        msg['body'] = utils.parseTemplate(template, params)
        
        utils.sendEmail(msg, format='html')
        
        return True
Esempio n. 24
0
    def test_validate_email(self):
        # These email addresses are correct
        email = '*****@*****.**'
        assert utils.validate_email(email) == True
        email = '*****@*****.**'
        assert utils.validate_email(email) == True
        email = '*****@*****.**'
        assert utils.validate_email(email) == True
        email = '[email protected]'
        assert utils.validate_email(email) == True
        email = 'test6.test$test%[email protected]'
        assert utils.validate_email(email) == True
        email = ('*****@*****.**'
                 'thisisprettyridiculous')
        assert utils.validate_email(email) == True

        # These email addresses are incorrect
        email = 'test@example'
        assert utils.validate_email(email) == False
        email = 'test.com'
        assert utils.validate_email(email) == False
        email = 'usernamenoatsymbol.com'
        assert utils.validate_email(email) == False
        email = ('*****@*****.**'
                 'arerulesafterall')
        assert utils.validate_email(email) == False

        # Empty string instead of email address
        email = ''
        assert utils.validate_email(email) == None
Esempio n. 25
0
def sign_up():
    """Sign up
    """
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        password_check = request.form['password-check']

        if username == None or len(username) == 0:
            # No username
            flash('Username is required.', 'error')
            return render_template('signup.html')

        if email == None or len(email) == 0:
            # No email
            flash('Email is required.', 'error')
            return render_template('signup.html')

        if password == None or len(password) == 0:
            # No password
            flash('Password is required.', 'error')
            return render_template('signup.html')

        if not validate_email(email):
            # Email is invalid
            flash('Email is invalid.', 'error')
            return render_template('signup.html')

        if password != password_check:
            # Passwords do not match
            flash('Passwords do not match.', 'error')
            return render_template('signup.html')

        if User.query.filter_by(username=username).first() != None:
            # Username already taken
            flash('Username is already taken.', 'error')
            return render_template('signup.html')

        if User.query.filter_by(email=email).first() != None:
            # Email already taken
            flash('Email is already taken.', 'error')
            return render_template('signup.html')

        try:
            u = User.create_user(username=username,
                                 email=email,
                                 password=password)
            db.session.add(u)
            db.session.commit()
        except:
            flash('Error occured during sign up.', 'error')
            return render_template('signup.html')

        flash('Successfully signed up!', 'info')
        return render_template('signup.html')

    else:
        if 'username' in session:
            return redirect('/')
        else:
            return render_template('signup.html')
Esempio n. 26
0
def edit_profile():
    """Edit profile information
    """

    if 'username' not in session:
        return redirect('/')

    u = User.query.filter_by(username=session['username']).first()

    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']

        if username == None or len(username) == 0:
            # No username
            flash('Username is required.', 'error')
            return render_template('edit_profile.html')

        if email == None or len(email) == 0:
            # No email
            flash('Email is required.', 'error')
            return render_template('edit_profile.html')

        if not validate_email(email):
            # Email is invalid
            flash('Email is invalid.', 'error')
            return render_template('edit_profile.html')

        other_u = User.query.filter_by(username=username).first()
        if other_u != None and other_u != u:
            # Username already taken
            flash('Username is already taken.', 'error')
            return render_template('edit_profile.html')

        other_u = User.query.filter_by(email=email).first()
        if other_u != None and other_u != u:
            # Email already taken
            flash('Email is already taken.', 'error')
            return render_template('edit_profile.html')

        # Update profile
        u.username = username
        u.email = email
        db.session.commit()

        # Update session
        session['username'] = username

        flash('Profile successfully updated!', 'info')
        return render_template(
            'edit_profile.html',
            username=u.username,
            email=u.email,
            score=u.score,
        )

    else:
        return render_template(
            'edit_profile.html',
            username=u.username,
            email=u.email,
            score=u.score,
        )
def test_validate_email():
    assert validate_email('fail') is False
    assert validate_email('') is False
Esempio n. 28
0
def signup():
    if config.REGISTRATION_ENABLED:
        if request.method == "POST":
            # Validate data
            form = request.form
            email = form.get("email").strip().lower()
            username = form.get("username").strip()
            display_name = form.get("display-name").strip()
            password = form.get("password").strip()
            confirm_password = form.get("confirm-password").strip()

            form_items = {
                k: v
                for k, v in request.form.items() if "password" not in k
            }

            if utils.validate_email(email):
                username_available, username_reason = utils.validate_username(
                    username)
                if username_available:
                    if password == confirm_password:
                        if password:
                            if captcha.verify():
                                # Use referral code if available
                                referral_code = form.get(
                                    "referral-code").strip()
                                referrer = None
                                if referral_code:
                                    referrer = models.ReferralCode.use(
                                        referral_code)

                                # Create user account
                                models.Crab.create_new(
                                    username=username,
                                    email=email,
                                    password=password,
                                    display_name=display_name,
                                    referrer=referrer,
                                    address=request.remote_addr,
                                )

                                # "Log in"
                                current_user = models.Crab.query.filter_by(
                                    username=username,
                                    deleted=False,
                                    banned=False,
                                ).first()
                                session["current_user"] = current_user.id
                                session[
                                    "current_user_ts"] = current_user.register_timestamp

                                # Redirect on success
                                return redirect("/signupsuccess")
                            else:
                                return utils.show_error(
                                    "Captcha verification failed",
                                    new_arguments=form_items,
                                )
                        else:
                            return utils.show_error(
                                "Password cannot be blank",
                                new_arguments=form_items,
                            )
                    else:
                        return utils.show_error(
                            "Passwords do not match",
                            new_arguments=form_items,
                        )
                else:
                    return utils.show_error(username_reason,
                                            new_arguments=form_items)
            else:
                return utils.show_error(
                    "An account with that email address already exists",
                    new_arguments=form_items,
                )

        elif session.get("current_user"):
            return redirect("/")
        else:
            signup_failed = request.args.get("failed") is not None
            error_msg = request.args.get("error_msg")
            return render_template(
                "signup.html",
                current_page="signup",
                hide_sidebar=True,
                signup_failed=signup_failed,
                error_msg=error_msg,
                referral_code=request.args.get("referral-code"),
            )
    else:
        return render_template(
            "registration-closed.html",
            current_page="registration-closed",
            hide_sidebar=True,
        )
Esempio n. 29
0
    if "apn" in settings:
        apn = settings["apn"]
        print("APN:", apn)

    if "email" in settings:
        email = settings["email"]
        print("Email:", email)

    if "name" in settings:
        name = settings["name"]
        print("Name:", name)

    if apn is not None and not utils.validate_apn(apn):
        print("Invalid APN!")
        apn = None
    if email is not None and not utils.validate_email(email):
        print("Invalid email!")
        email = None
    if name is None:
        name = "Polaris"
        print("Saving name:", name)
        settings["name"] = name
        utils.saveSettings(settings)
    if apn is None:
        print("APN is not defined, can't connect to Internet!")
        apn = utils.request_apn(s)
        print("Saving APN:", apn)
        settings["apn"] = apn
        utils.saveSettings(settings)
    if email is None:
        print("email is not defined, can't register to Cloud!")
Esempio n. 30
0
def sign_up():
    if redirect_is_logged(session) != True:
        return redirect_is_logged(session)
    page_name = "login - sign up"
    valid = True
    error_array = {}
    if request.method == 'POST':

        fullname = request.form.get('fullname', None)
        username = request.form.get('username', None)
        email = request.form.get('email', None)
        password = request.form.get('password', None)
        repeat_password = request.form.get('repeat_password', None)

        if validate_password(password) == False:
            error_array['password'] = '******'
            valid = False

        if password != repeat_password:
            error_array['password_repeat'] = 'password does\'nt match'
            valid = False

        if len(fullname) < 2:
            error_array['fullname'] = 'fullname too short'
            valid = False

        if validate_username(username) == False:
            error_array['username'] = '******'
            valid = False

        if User.query.filter_by(username=username).first() is not None:
            error_array['username'] = '******'
            valid = False

        if validate_email(email) == False:
            error_array['email'] = 'email is not valid'
            valid = False

        if User.query.filter_by(email=email).first() is not None:
            error_array['email'] = 'email is already taken'
            valid = False

        if valid == True:
            user = User(username=username,
                        full_name=fullname,
                        email=email,
                        password=password)
            db.session.add(user)
            db.session.commit()

            if user == False:
                error_array['system'] = 'error insert db'
            else:
                session['id'] = user.id
                session['username'] = username
                session['full_name'] = fullname
                session['email'] = email
                # return render_template('index.html', page_name='Home', session=session)
                return redirect(url_for('index'))

    return render_template('login.html',
                           page_name=page_name,
                           error_array=error_array)