def post(self):
        """ Handler to login and retrieve a secure cookie.

        +--------------------------------------------------------------------+
        | Example                                                            |
        +====================================================================+
        | http://example.com/login                                           |
        | {"username" : USERNAME, "password" : PASSWORD}                     |
        +--------------------------------------------------------------------+

        .. note:: The parameters for the POST calls have to be posted in the \
                    body as a JSON object.

        :param string username: Experiment ID as specified in the url.
        :param string password: The number of simulation draws.
        :raises 401: If wrong username or password.
        """
        # Get config:
        users = Users()

        data = tornado.escape.json_decode(self.request.body)

        # Check:
        username = data["username"]
        password = data["password"]
        user_id = users.get_user_info(username, password)
        if user_id is not None and user_id is not False:
            self.set_secure_cookie("user", str(user_id))
            self.finish()
        else:
            # Add user feedback!
            raise ExceptionHandler(reason="Wrong username or password!",
                                   status_code=401)
    def post(self):
        """ Add a user to StreamingBandit.

        +--------------------------------------------------------------------+
        | Example                                                            |
        +====================================================================+
        | http://example.com/user                                            |
        | {"username" : USERNAME, "password" : PASSWORD}                     |
        +--------------------------------------------------------------------+

        .. note:: The parameters for the POST calls have to be posted in the \
                    body as a JSON object.

        :param string username: The preferred username.
        :param string password: The preferred password.
        :returns: JSON indicating success.
        :raises 400: If user with username already exists.
        """
        if self.valid_admin():
            data = tornado.escape.json_decode(self.request.body)
            users = Users()
            username = data["username"]
            password = data["password"]
            user_id = users.create_user(username, password)
            if user_id is False:
                raise ExceptionHandler(reason="User already exists.",
                                       status_code=400)
            else:
                self.write(json.dumps({'status': 'success'}))
        else:
            raise ExceptionHandler(reason="You are not an admin.",
                                   status_code=401)
Exemple #3
0
 def gconnect(self):
     ''' Ensures that google authenticated our website user and stores their
     credentials and information in a temporary session.
     '''
     # Get the OAuth2 code and try to retrieve credentials with it
     code = request.data
     try:
         oauth_flow = flow_from_clientsecrets(os.path.join(
             os.path.dirname(__file__), '../google_cs.json'),
                                              scope='')
         oauth_flow.redirect_uri = 'postmessage'
         credentials = oauth_flow.step2_exchange(code)
     except FlowExchangeError:
         return self.invalid_response(
             'Failed to upgrade the authorization code', status_code=401)
     # Check the access token
     access_token = credentials.access_token
     url = (
         'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={0}'.
         format(access_token))
     h = httplib2.Http()
     result = json.loads(h.request(url, 'get')[1])
     if result.get('error') is not None:
         return self.invalid_response(result.get('error'), status_code=500)
     # Get the users Google ID and check it against the access token user id
     google_id = credentials.id_token['sub']
     if result['user_id'] != google_id:
         return self.invalid_response('The IDs do not match.',
                                      status_code=401)
     # Get the user's data
     userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
     params = {'access_token': credentials.access_token, 'alt': 'json'}
     answer = requests.get(userinfo_url, params=params)
     data = answer.json()
     # Try to use the currently logged in user
     user = g.get('user')
     # If no user is logged in, see if a user exists
     if user is None:
         user = g.db.query(Users).filter_by(email=data['email']).first()
     # If no user exists, create one
     if user is None:
         user = Users(name=data['name'],
                      email=data['email'],
                      provider='google')
         g.db.add(user)
         g.db.commit()
     else:
         user.provider = 'google'
         g.db.add(user)
         g.db.commit()
     # Store the user data in the session
     session['user_id'] = user.id
     session['access_token'] = access_token
     # Notify the user and redirect to the home page
     flash('Successfully logged in as {0}'.format(user.name), "success")
     return redirect(url_for('landing'))
Exemple #4
0
 def __init__(self, db):
     # self.main_db = TablesController(db, "_en")
     # self.draw = CardsPicker(self.main_db)
     self.db = db
     self.uploads = Uploads(db, 'uploads')
     self.avatars = DbHelper(db, 'avatars')
     self.users = Users(db, 'users')
     self.bookmarks = DbHelper(db, 'bookmarks')
     self.decks = DbHelper(db, 'decks')
     self.alt_deck = Deck(db)
     self.alt_picker = AltPicker(self.alt_deck)
Exemple #5
0
    async def for_file(self, file_id):
        users = Users()
        q = self.select(self.table.star, users.table.username)\
            .join(users.table).on(users.table.id == self.table.by_user_id)\
            .where(self.table.file_id == file_id)\
            .orderby('id', order=Order.desc)

        data = await self.fetch(q)
        return [self.to_json(d) for d in data]
Exemple #6
0
 def fbconnect(self):
     ''' Connects to Facebook '''
     data = request.get_json()
     if data.get('id'):
         del data['id']
     # Get the user or create a new one
     user = g.db.query(Users).filter_by(email=data['email']).first()
     if user is None:
         user = Users(**data)
         user.provider = 'facebook'
         g.db.add(user)
         g.db.commit()
     else:
         user.provider = 'facebook'
         g.db.add(user)
         g.db.commit()
     # Store the user data in the session
     session['user_id'] = user.id
     return redirect(url_for('landing'))
Exemple #7
0
    async def get(self, request):
        is_admin(request)
        q = request.path_params.get('q')
        offset = request.path_params.get('offset')
        limit = request.path_params.get('limit')

        async with get_conn() as conn:
            data = await Users(conn).get_users(offset=offset,
                                               limit=limit,
                                               username=q)

        return UJSONResponse({'data': [Users.to_json(u) for u in data]})
Exemple #8
0
from flask_pymongo import MongoClient
from db.users import Users
from config import db_url

users = Users(MongoClient(db_url))

from api.methods import ApiMethods

api = ApiMethods(users)
Exemple #9
0
class Controller:
    def __init__(self, db):
        # self.main_db = TablesController(db, "_en")
        # self.draw = CardsPicker(self.main_db)
        self.db = db
        self.uploads = Uploads(db, 'uploads')
        self.avatars = DbHelper(db, 'avatars')
        self.users = Users(db, 'users')
        self.bookmarks = DbHelper(db, 'bookmarks')
        self.decks = DbHelper(db, 'decks')
        self.alt_deck = Deck(db)
        self.alt_picker = AltPicker(self.alt_deck)

    def create_user(self, data):
        data["type"] = "user"
        data["avatar_id"] = self.pick_avatar()
        user_id = self.users.add(data)
        return user_id

    def pick_avatar(self):
        avatars = self.avatars.list()
        id = randint(0, len(avatars) - 1)
        return avatars[id]['id']

    #formats data into upload format and returns filename, id
    def create_upload(self, user_id, file_extention):
        data = {'user_id': user_id}
        id = self.uploads.add(data)
        filename = "img" + str(id) + file_extention
        image_data = {'id': id, 'filename': filename}
        return image_data

    #from array shaped string, format data into bookmark format
    def create_bookmark(self, user_id, cards):
        cards_string = join(str_arr(cards))
        #sends data dict to db manager
        data = {'user_id': user_id, 'cards': {'input_text': cards_string}}
        self.bookmarks.add(data)

    def delete_upload(self, item_id):
        file = self.uploads.find(item_id)[0]
        if os.path.isfile(file['path']):
            os.remove(file['path'])
        self.uploads.delete(item_id)

    #formats cards and sends to db
    def update_upload(self, image_id, imd):
        data = {}
        data['cards'] = cards_imd(imd)
        print("-----in update print data:")
        print(data)
        self.uploads.update(image_id, data)

    def update_user_avatar(self, user_id):
        data = {}
        data['avatar_id'] = self.pick_avatar()
        self.users.update(user_id, data)

    def read(self, data):
        parse = ['cards']
        for row in data:
            for col in row:
                if col in parse:
                    row[col] = split(row[col])
        print("-----in read print data:")
        print(data)
        return data

    def user_bookmarks(self, user_id):
        all = self.bookmarks.all_from_user(user_id)
        for item in all:
            item['cards'] = split(item['cards'])
        return all

    def write(self, array):
        return join(array)

    def custom_deck(self, user_id, deck_id):
        if type(deck_id) != str:
            deck_id = str(deck_id)
        self.alt_deck.load(deck_id)

    def delete_deck(self, deck_id):
        self.alt_deck.clear_deck_data(deck_id)
        self.decks.delete(deck_id)

    def delete_user(self, user_id):
        uploads = self.uploads.all_from_user(user_id)
        decks = self.decks.all_from_user(user_id)
        bookmarks = self.bookmarks.all_from_user(user_id)

        for upload in uploads:
            self.delete_upload(upload['id'])
        for deck in decks:
            self.delete_deck(deck['id'])
        for bookmark in bookmarks:
            self.bookmarks.delete(bookmark['id'])

        self.users.delete(user_id)
Exemple #10
0
from db.users import Users

# Create the database if it doesn't exist
if not database_exists(engine.url):
    create_database(engine.url)

# Create the user table
Base.metadata.create_all(engine)

# Create the user with id 1
DEMO = {
    'id': 1,
    'username': '******',
    'password': '******',
    'first_name': 'Kevin',
    'last_name': 'Rivers'
}

# Hash user password with bcrypt(12)
DEMO['password'] = bcrypt.hashpw(DEMO['password'].encode(),
                                 bcrypt.gensalt()).decode()

u = Users(**DEMO)
session.add(u)

try:
    session.commit()
except IntegrityError:
    # We  have already added the demo user with id 1
    pass