Beispiel #1
0
    def post(self):
        json_data = request.get_json()
        data = user_schema.load(json_data)
        admin = check_admin(data.get("admin_pass"))
        data = UserSchema(unknown=EXCLUDE).load(json_data)

        if User.get_by_username(data.get("username")) or User.get_by_email(
                data.get("email")):
            return {
                "message": "Username or email already taken"
            }, HTTPStatus.BAD_REQUEST

        if admin and check_email(data.get("email")):
            user = User(is_admin=True, is_turkuamk=True, **data)
            user.save()
            return UserSchema().dump(user), HTTPStatus.CREATED

        elif check_email(data.get('email')):
            user = User(is_turkuamk=True, **data)
            user.save()
            return user_schema_noadm.dump(user), HTTPStatus.CREATED

        else:
            user = User(**data)
            user.save()
            return user_schema_outsider.dump(user), HTTPStatus.CREATED
Beispiel #2
0
 def test_check_email(self):
   assert check_email('') is not None
   assert check_email('ben') is not None
   assert check_email('ben@mit') is not None
   assert check_email('[email protected]') is not None
   assert check_email('[email protected]') is not None
   assert check_email('@mit.edu') is not None
   assert check_email('ben%mit.edu') is not None
   assert check_email('*****@*****.**') is None
   assert check_email('*****@*****.**') is None
Beispiel #3
0
 def clean_email(self):
     email = self.cleaned_data.get('email')
     if email:
         email = email.strip()
         if not check_email(email):
             raise forms.ValidationError(cn_key._email_error)
     return email
Beispiel #4
0
def handle_checkall(message):
    _logger.info("/checkall")
    user = db.get_user(message.from_user.id)[0]
    emails = [] if 'emails' not in user else user['emails']
    if not emails:
        bot.reply_to(message, 'No has registrado emails todavía. Utiliza /newemail para ello.')
    flag_update_urls = False
    for email in emails:
        urls = [] if 'urls' not in email else email['urls']
        urls_data = [url['url'] for url in urls]
        json_data = check_email(email['email'])
        lines = show_data(json_data)
        if lines:
            bot.reply_to(message, "%s con resultados..." % email['email'])
            for line in lines:
                registered = False
                if line[1] in urls_data:
                    registered = True
                    break
                if not registered:
                    urls += [{'url': line[1]}]
                    flag_update_urls =True
                line_str = ' '.join(line)
                bot.send_message(user['id'], line_str)
            email['urls'] = urls
        else:
            bot.send_message(user['id'], "%s Todo OK!" % email['email'])
    if flag_update_urls:
        db.register_emails(user['id'], emails)
Beispiel #5
0
    def post(self):

        param = {
            'username': fields.String(),
            'password': fields.String(),
            'email': fields.String()
        }
        try:
            json_data = parse_req(param)
            username = json_data.get('username', None)
            password = json_data.get('password', None)
            email = json_data.get('email', None)

        except Exception:
            return jsonify("An error occurred when getting data !")

        query_user = {
            '_id': str(ObjectId()),
            'username': username,
            'password': password,
            'email': email,
            'first_login': True
        }

        try:
            find_person = mycol.find_one({'username': username})
            if find_person is not None:
                return jsonify("Username is already exist")
            if check_email(email) is None:
                return jsonify("Invalidate email !")
            else:
                mycol.insert_one(query_user)
                return jsonify("Register successfully !")
        except Exception:
            return jsonify("An error occurred when inserting data !")
Beispiel #6
0
def register():
  """
  Attempts to register the user with the given account information.
  """
  name = request.form['name']
  email = request.form['email']
  password = request.form['password']
  repassword = request.form['repassword']
  name_error = check_name(name)
  if name_error != None:
    # malformed name
    return jsonify({'type': 'error', 'error': name_error})
  email_error = check_email(email)
  if email_error != None:
    # malformed e-mail
    return jsonify({'type': 'error', 'error': email_error})
  password_error = check_password(password, repassword)
  if password_error != None:
    # malformed password
    return jsonify({'type': 'error', 'error': password_error})
  user_exists = db.user_exists(email)
  if user_exists:
    # user with this e-mail already exists
    error = 'An account with this e-mail address already exists!'
    return jsonify({'type': 'error', 'error': error})
  user = db.make_user(name, email, password)
  flash('Welcome to Bookmark+, %s!' % user.name)
  session['user_id'] = unicode(user._id)
  return jsonify({'type': 'success', 'url': url_for('home')})
Beispiel #7
0
def register():
    if current_user.is_authenticated:
        return redirect('/')

    form = RegisterForm()
    if form.validate_on_submit():
        name = request.form.get('username')
        login = request.form.get('login')

        if db_additions.check_login(login):
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   errors="Данный логин занят.")
        hashed_password = generate_password_hash(request.form.get('password'))

        if not utils.check_email(request.form['email']):
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   errors="Неправильный формат почты.")
        email = request.form.get('email')
        if db_additions.check_mail(email):
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   errors='Данная почта уже используется.')
        user = db_additions.register_user(login, hashed_password, email, name)
        return redirect('/login')
    return render_template('register.html', title='Регистрация', form=form)
Beispiel #8
0
def create_user():
    email_valid = False
    while True:
        if not email_valid:
            email = input("Email: ")
            email_valid = check_email(email)
            if not email_valid:
                print("***Invalid email address***")
                continue

            user = cursor.execute(
                f'SELECT * FROM USER WHERE EMAIL="{email}";').fetchone()
            if user:
                print("***Email address already exists***")
                email_valid = False
                continue
            email_valid = True

        password = getpass.getpass()
        if len(password) < 6:
            print("***Password must have min 6 characters***")
            continue
        confirm_pass = getpass.getpass(prompt="Confirm password: "******"***Passwords do not match***")
            continue

        cursor.execute(
            f"Insert Into USER ('EMAIL','PASSWORD') Values ('{email}', '{generate_password_hash(password)}');"
        )
        conn.commit()
        print("***User has been created successfully!***")
        break
Beispiel #9
0
 def clean_email(self):
     email = self.cleaned_data.get('email')
     if email:
         email = email.strip()
         if not check_email(email):
             raise forms.ValidationError(cn_key._email_error)
     return email
Beispiel #10
0
    def clean_email(self):
        """ Check to see if email address exists and vouched for by the provider """

        email = self.cleaned_data['email']
        from_host = self.site.domain
        from_email = 'verify@{0}'.format(from_host)
        if 'spamware' in settings.INSTALLED_APPS:
            if not check_email(email, from_host, from_email):
                raise forms.ValidationError(_("Email address does not exist. Please enter a valid email."))
        return email
Beispiel #11
0
 def post(self):
     user_username = self.request.get("username")
     user_password = self.request.get("password")
     user_verify = self.request.get("verify")
     user_email = self.request.get("email")
     
     uname = user_username
     email = user_email
     
     uname_err = utils.check_username(user_username)
     pw_err=""
     vpw_err=""
     email_err=""
     
     Success= True
     
     if uname_err != "":
         Success= False
         
     if utils.check_password(user_password)==False:
         pw_err="That's not a valid password."
         Success= False
     
     if utils.verify_password(user_password, user_verify)==False:
         vpw_err="Your passwords didn't match."
         Success= False
     if len(email) != 0:
         if utils.check_email(user_email)==False:
             email_err="That's not a valid email."
             Success= False
     
     if Success:
         x = utils.make_pw_hash(uname, user_password)
         saltedPass = x.split("|")[0]
         salt = x.split("|")[1]
         
         if len(email) != 0:
             newUser = User(key_name = uname, username = uname, email=email, password = saltedPass, salt = salt)
         else:
             newUser = User(key_name = uname, username = uname, password = saltedPass, salt = salt)
         newUser.put()
         setUser = "******" + uname
         self.response.headers.add_header('Set-Cookie', setUser.encode())
         self.redirect("/")
     else:
         self.render_signup(uname, email,uname_err, pw_err, vpw_err,email_err)
Beispiel #12
0
    def post(self):
        response = {}
        username = str(self.get_body_argument("username", ''))
        password = str(self.get_body_argument("password", ''))
        email = str(self.get_body_argument("email", ''))
        coutry = str(self.get_body_argument("coutry", ''))
        if not check_uname_passwd(username, password) or not check_email(email):
            self.set_status(400)
            response['msg'] = "The type of username or password or email is error"
            self.write(response)
            return

        user_id = shortid_generate()
        passwd = passwd_hash(str(password))
        user = {'id': user_id, 'username': str(username), 'password': passwd, 'email': str(email), 'coutry': coutry, 'admin_auth': False, 'score': 0, 'banned': False}
        db_uname, db_email = yield [self.db.users.find({'username': str(username)}).count(), self.db.users.find({'email': str(email)}).count()]
        if db_uname or db_email:
            self.set_status(400)
            if db_email and db_uname:
                response['msg'] = "The email and username have exited"
            elif db_email:
                response['msg'] = "The email have exited"
            else:
                response['msg'] = "The username have exited"
            self.write(response)
            return

        try:
            result = yield self.db.users.insert(user)
        except Exception as e:
            # add log here
            self.set_status(404)
            response['msg'] = "Register Error."
            self.write(response)
            return
        if result:
            self.set_status(201)
            response['msg'] = "Register Success"
            self.write(response)
            return
        else:
            self.set_status(404)
            response['msg'] = "Register Error"
            self.write(response)
            return
Beispiel #13
0
 def clean_email(self):
     email = self.cleaned_data.get('email')
     if email:
         email = email.strip()
         if not check_email(email):
             raise forms.ValidationError(cn_key._email_error)
         try:
             User.objects.get(uid=email)
             raise forms.ValidationError(cn_key._email_exists)
         except User.DoesNotExist:
             pass
         try:
             User.objects.get(email=email)
             raise forms.ValidationError(cn_key._email_exists)
         except User.DoesNotExist:
             pass
     else:
         raise forms.ValidationError(cn_key._email_required)
     return email
Beispiel #14
0
 def clean_email(self):
     email = self.cleaned_data.get('email')
     if email:
         email = email.strip()
         if not check_email(email):
             raise forms.ValidationError(cn_key._email_error)
         try:
             User.objects.get(uid=email)
             raise forms.ValidationError(cn_key._email_exists)
         except User.DoesNotExist:
             pass
         try:
             User.objects.get(email=email)
             raise forms.ValidationError(cn_key._email_exists)
         except User.DoesNotExist:
             pass
     else:
         raise forms.ValidationError(cn_key._email_required)
     return email
Beispiel #15
0
def register_admin():
    if current_user.role != 'admin':
        return 'вы не администратор'

    name = request.form.get('username')
    login = request.form.get('login')

    if db_additions.check_login(login):
        return 'данный логин занят'
    hashed_password = generate_password_hash(request.form.get('password'))

    email = request.form.get('email')
    if not check_email(email):
        return 'неправильный формат почты'

    if db_additions.check_mail(email):
        return 'Данная почта уже используется.'
    print(name, login, email)
    db_additions.register_admin(login, hashed_password, email, name)

    return 'success'
Beispiel #16
0
def check(bot=False, confile=False):
    if not bot and confile:
        Config = ConfigParser.ConfigParser()
        Config.read(confile)
        HSHBOT_TOKEN = Config.get('options', 'api_token')
        bot = telebot.TeleBot(HSHBOT_TOKEN)
        HSHBOT_ADMIN_ID = int(Config.get('options', 'admin_id') or False)
    elif bot:
        HSHBOT_ADMIN_ID = int(os.environ['HSHBOT_ADMIN_ID'])
    else:
        _logger.error("Cron execution error, bot and confile not found!")
        sys.exit()

    _logger.info("cron:: check()")

    if HSHBOT_ADMIN_ID:
        bot.send_message(HSHBOT_ADMIN_ID, '[INFO] Iniciando cron.check()...')

    users = db.get_users()
    emails_checked = {}

    try:
        for user in users:
            user_emails = [] if 'emails' not in user else user['emails']
            if not user_emails:
                bot.send_message(
                    user['id'],
                    "Se ha ejecutado el checkeo de emails, y veo que no tienes ninguno registrado "
                    "aún...\nRecuerda que puedes hacerlo con /newemail"
                )
            flag_update_urls = False
            for user_email in user_emails:
                email_urls = [] if 'urls' not in user_email else user_email['urls']
                email_urls_data = [email_url['url'] for email_url in email_urls]
                flag_notification = False
                if user_email['email'] not in emails_checked:
                    try:
                        json_data = check_email(user_email['email'])
                    except Exception, e:
                        if HSHBOT_ADMIN_ID:
                            bot.send_message(HSHBOT_ADMIN_ID, '[ERROR] HeSidoHackeadoBot is down!')
                        raise e
                    emails_checked[user_email['email']] = show_data(json_data)
                if emails_checked[user_email['email']]:
                    for line in emails_checked[user_email['email']]:
                        registered = False
                        if line[1] in email_urls_data:
                            registered = True
                            break
                        if not registered:
                            line_str = ' '.join(line)
                            if not flag_notification:
                                flag_notification = True
                                bot.send_message(user['id'], "%s con resultados..." % user_email['email'])
                            bot.send_message(user['id'], line_str)
                            email_urls += [{'url': line[1]}]
                            flag_update_urls = True
                    user_email['urls'] = email_urls
                # if not flag_notification:
                #     bot.send_message(user['id'], "%s Todo OK!" % user_email['email'])
            if flag_update_urls:
                db.register_emails(user['id'], user_emails)
    except Exception, e:
        pass
Beispiel #17
0
 def check_email(self, email):
     if not check_email(email):
         self.return_error(30218)
Beispiel #18
0
 def clean_email(self):
     email = super(SignupForm, self).clean_email()
     if check_email(email):
         return email
     raise forms.ValidationError(_("Email address does not exist. Please try again."))