Example #1
0
def reset_password_action():  
    hash = request.form["hash"]
    id = request.form["id"]
    password = request.form["password"]
    password2 = request.form["password2"]
    token = request.form["token"]
    
    error = validateResetForm(id, hash)
    
    if not error:
        if not password:
            error = 'Please enter a password'
        elif not password2:
            error = 'Please enter a password'
        elif password != password2:
            error = 'Passwords do not match'
        else:
            bcrypt = Bcrypt(app)
            pwHash = bcrypt.generate_password_hash(password)
            
            usersService = UsersService()
            userResult = usersService.first(id=int(id))
            
            usersService.update(userResult, password=pwHash)
            error = 'Password updated'
        
    return render_custom_template('login/reset_password.html', id=id, hash=hash, error=error)
Example #2
0
def signup():
    form = SignupForm()
    bcrypt = Bcrypt(app)
    if 'user_id' in session:
        return redirect(url_for('profile'))
    
     
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('signup.html', form=form)
        else:
            password = bcrypt.generate_password_hash(form.su_password.data,10)
            cursor= cnx.cursor()
            cursor.callproc('create_new_user',[form.su_username.data,form.su_firstname.data, form.su_lastname.data, form.su_email.data,password])
            user_id = cursor.fetchone()
            cursor.close()
        if request.method == 'POST':    
            rolelist = RoleList(user_id[0])
            session['user_id'] = user_id[0]
            session['roles'] = rolelist.roles
            
            
            return redirect(url_for('profile')) 
     
    elif request.method == 'GET':
        return render_template('signup.html', form=form)
Example #3
0
    def setUp(self):
        self.app = application.app
        bcrypt = Bcrypt(self.app)

        # forcibly reconnect to testing db
        connection.disconnect()
        self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing'
        self.connection = connect(
            self.app.config['MONGO_CONFIG']['db_name']
            , host=self.app.config['MONGO_CONFIG']['host']
            , port=int(self.app.config['MONGO_CONFIG']['port'])
        )
        # drop any lingering test dbs
        self.connection.drop_database(
            self.app.config['MONGO_CONFIG']['db_name'])

        member_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        member_user.save()

        ''' create a test org
        '''
        test_org = Organization(
            label = 'best-org'
            , name = 'best org')
        test_org.save()

        # save membership
        member_user.update(push__organizations = test_org)

        ''' create a test project
        '''
        test_project = Project(
            creation_time = datetime.datetime.utcnow()
            , label = 'best-project'
            , name = 'best project'
            , organization = test_org)
        test_project.save()
        test_org.update(push__projects=test_project)

        ''' create a data-less upload
        '''
        '''
Example #4
0
def register_action():
    username = request.form["username"]
    email = request.form["email"]
    password = request.form["password"]
    password2 = request.form["password2"]
    token = request.form["token"]
    
    print email
    
    usersService = UsersService()
    
    if username:
        usernameResult = usersService.first(username=username)
    else:
        usernameResult = False
        
    if email:    
        emailResult = usersService.first(email=email)
    else:
        emailResult = False
        
    #do validation checking
    if not username:
        error = 'Please enter a username'
    elif usernameResult:
        error = 'Username has been taken'
    elif not email:
        error = 'Please enter an email address'
    elif emailResult:
        error = 'Email address has been taken'
    elif not password:
        error = 'Please enter a password'
    elif password != password2:
        error = 'Passwords do not match'
    elif not isTokenValid(token):
        error = 'The request did not come from Pycamp'    
    else:
        error = False
    
    #error = True
        
    if not error: 
        bcrypt = Bcrypt(app)
        pwHash = bcrypt.generate_password_hash(password)
           
        usersService.create(username=username, email=email, password=pwHash, salt='', role_id=2, forgot_password_hash='')
    
    return render_custom_template('register/index.html', error=error, username=username, email=email)
    
Example #5
0
class BasicTestCase(unittest.TestCase):
    
    def setUp(self):
        app = flask.Flask(__name__)
        app.config['BCRYPT_LOG_ROUNDS'] = 6
        self.bcrypt = Bcrypt(app)
        
    def test_is_string(self):
        pw_hash = self.bcrypt.generate_password_hash('secret')
        self.assertTrue(isinstance(pw_hash, str))
        
    def test_not_string(self):
        pw_hash = self.bcrypt.generate_password_hash(42)
        self.assertTrue(isinstance(pw_hash, str))
        
    def test_custom_rounds(self):
        password = '******'
        pw_hash1 = self.bcrypt.generate_password_hash(password, 5)
        self.assertNotEqual(password, pw_hash1)
    
    def test_check_hash(self):
        pw_hash = self.bcrypt.generate_password_hash('secret')
        # check a correct password
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret'))
        # check an incorrect password
        self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2'))
        # check unicode
        pw_hash = self.bcrypt.generate_password_hash(u'\u2603')
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603'))
        # check helpers
        pw_hash = generate_password_hash('hunter2')
        self.assertTrue(check_password_hash(pw_hash, 'hunter2'))
    
    def test_check_hash_unicode_is_utf8(self):
        password = u'\u2603'
        pw_hash = self.bcrypt.generate_password_hash(password)
        # check a correct password
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, '\xe2\x98\x83'))
    
    def test_rounds_set(self):
        self.assertEquals(self.bcrypt._log_rounds, 6)
Example #6
0
    app.config.from_pyfile(app.config['CFG_FILE'])
except IOError:
    pass


from fileStore import *
db = fileStore(app.config['CACHE_ROOT'] + '/db')

# load config from the database
conf = None
try:
    conf = json.loads(db.get('conf/bradmin'))    
except IOError:
    # load default config
    conf = { 
        'password': bcrypt.generate_password_hash('default')
        }
    db.store('conf/bradmin', json.dumps(conf, sort_keys=True, indent=4))

application = app

import bradmin.login
import bradmin.push

#web pages
import bradmin.frontpage
import bradmin.settings
import bradmin.radio
import bradmin.clouds
import bradmin.mesh
Example #7
0
    def setUp(self):
        self.app = application.app
        bcrypt = Bcrypt(self.app)

        # forcibly reconnect to testing db
        connection.disconnect()
        self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing'
        mongo_config = self.app.config['MONGO_CONFIG']
        mongodb_uri = 'mongodb://'
        if mongo_config['dbuser'] and mongo_config['dbpassword']:
            mongodb_uri += '%s:%s@' % (mongo_config['dbuser']
                    , mongo_config['dbpassword'])
        mongodb_uri += '%s/%s' % (mongo_config['hosts'], mongo_config['db_name'])
        self.connection = connect(mongo_config['db_name'], host=mongodb_uri)

        # drop any lingering test dbs
        self.connection.drop_database(
            self.app.config['MONGO_CONFIG']['db_name'])

        ''' create test user
        '''
        member_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.utcnow()
            , verified = True)
        member_user.save()

        ''' create test org
        '''
        test_org = Organization(
            label = 'euro-water'
            , name = 'Euro Water')
        test_org.save()
        # save membership
        member_user.update(push__organizations = test_org)

        ''' create test headers
        '''
        date_header = Header(data_type = 'datetime', name = 'date',
                label = 'date')
        date_header.save()

        pH_header = Header(data_type = 'number', name = 'pH', label = 'pH')
        pH_header.save()

        city_header = Header(data_type = 'string', name = 'city',
                label = 'city')
        city_header.save()
        headers = [date_header, pH_header, city_header]

        # save ref to this header for later test
        self.date_header_id = date_header.id

        ''' create test project
        '''
        test_project = Project(
            creation_time = datetime.utcnow()
            , label = 'water-quality'
            , name = 'water quality'
            , ordered_schema = headers
            , organization = test_org)
        test_project.save()
        test_org.update(push__projects=test_project)

        ''' update the headers with a ref to the project
        '''
        for header in headers:
            header.update(set__project = test_project)

        ''' create test datapoints
        '''
        test_data = [
            {'date': datetime(2012, 3, 4), 'pH': 2.2, 'city': 'Madrid'}
            , {'date': datetime(2012, 3, 5), 'pH': 3, 'city': 'Paris'}
            , {'date': datetime(2012, 3, 6), 'pH': 4, 'city': 'London'}
            , {'date': datetime(2012, 3, 6), 'pH': 3, 'city': 'London'}
            , {'date': datetime(2012, 3, 6), 'pH': None, 'city': 'London'}
        ]
        for datapoint in test_data:
            new_entry = Entry(
                project = test_project
                , unique = True
                , values = datapoint)
            new_entry.save()
Example #8
0
        # Hack: version is initialized to 0.1 in order to manage table migration
        db.session.add(Config('version', '0.1'))
        db.session.commit()

# Database migration
if versiontuple(get_config('version')) < versiontuple('0.2'):
    # From 0.1 to 0.2
    print " * Upgrade to v0.2"
    engine = create_engine('sqlite:///kafein/kafein.db', echo=False)
    conn = engine.connect()
    try:
        conn.execute('ALTER TABLE post ADD COLUMN static BOOLEAN')
        conn.execute('UPDATE post SET static=0')
        conn.execute('ALTER TABLE user ADD COLUMN deleted BOOLEAN')
        conn.execute('UPDATE user SET deleted=0')
    except:
        print "New install"
    conn.close()
    set_config('version', '0.2')

if len(models.User.query.all()) == 0:
    pw_hash = bcrypt.generate_password_hash(app.config['DEFAULT_PASSWORD'])
    db.session.add(models.User(0, app.config['DEFAULT_USERNAME'], pw_hash))
    db.session.commit()

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

import views
Example #9
0
class UserApi(Resource):

    def __init__(self):
        self.db = current_app.config['DB']
        self.bcrypt = Bcrypt(current_app)

    def abort(self, response=None):
        if response is None:
            abort(400)
        return (response, 400)

    def prettify(self, user):
        return {
            'login': user['login'],
            'role': 'Admin' if user['admin'] else 'User'
        }

    def find_user(self, login=None):
        if login is None:
            login = request.json['login']
        return self.db.User.find_one({'login': login})

    def get(self, login=None):
        if login:
            user = self.find_user(login)
            if user:
                return self.prettify(user)
        else:
            return [
                self.prettify(r) for r in self.db.User.find()
            ]

    def post(self):
        if request.json is None:
            return self.abort({'message': "Data required"})
        if self.find_user():
            return {'message': "User already exists"}
        user = self.db.User()
        user['login'] = request.json['login']
        user['password'] = self.bcrypt.generate_password_hash(
            request.json['password']
        )
        user.save()
        return ({'message': 'User created successfully!'}, 201)

    def put(self, login):
        user = self.find_user(login)
        if user is None:
            return self.abort({'message': "User not found"})
        curr_pass = request.json.get('current_password', '')
        if not self.bcrypt.check_password_hash(
                user['password'], curr_pass):
            return self.abort({'message': "Invalid password"})
        new_pass = request.json.get('new_password', '')
        if new_pass ==  curr_pass:
            return self.abort({'message': "New password should be different than the old one"})
        confirm_pass = request.json.get('confirm_password')
        if not new_pass:
            return self.abort({'message': "Please provide new password"})
        if new_pass != confirm_pass:
            return self.abort({'message': "New password confirmed incorrectly"})
        user = self.db.User(user)
        user['password'] = self.bcrypt.generate_password_hash(
            request.json['new_password']
        )
        user.save()
        return {'message': "Password changed"}

    def delete(self, login):
        user = self.find_user(login)
        if user:
            self.db.User(user).delete()
        else:
            return self.abort({'message': "User was not found"})
        if self.find_user(login) is not None:
            return self.abort({'message': "User still exists"})
        return {'message': "User deleted successfully"}
Example #10
0
 def passwd(self, value=None):
     bcrypt = Bcrypt()
     password = bcrypt.generate_password_hash(value)
     self.password = password
Example #11
0
    def setUp(self):
        self.app = application.app
        bcrypt = Bcrypt(self.app)

        # forcibly reconnect to testing db
        connection.disconnect()
        self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing'
        mongo_config = self.app.config['MONGO_CONFIG']
        mongodb_uri = 'mongodb://'
        if mongo_config['dbuser'] and mongo_config['dbpassword']:
            mongodb_uri += '%s:%s@' % (mongo_config['dbuser']
                    , mongo_config['dbpassword'])
        mongodb_uri += '%s/%s' % (mongo_config['hosts'], mongo_config['db_name'])
        self.connection = connect(mongo_config['db_name'], host=mongodb_uri)

        # drop any lingering test dbs
        self.connection.drop_database(
            self.app.config['MONGO_CONFIG']['db_name'])

        admin_user = User(
            admin_rights = True
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        admin_user.save()

        # same as verified but will push into an org for membership
        member_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        member_user.save()

        verified_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        verified_user.save()

        unverified_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = False)
        unverified_user.save()

        ''' create a test org
        '''
        test_org = Organization(
            label = 'best-org'
            , name = 'best org')
        test_org.save()

        # save membership
        member_user.update(push__organizations = test_org)

        ''' create a test project
        '''
        test_project = Project(
            creation_time = datetime.datetime.utcnow()
            , label = 'best-project'
            , name = 'best project'
            , organization = test_org)
        test_project.save()
        test_org.update(push__projects=test_project)