Exemple #1
0
    def createToken(self, args):
        self._start(args)
        # Do a check to see if any admins exist before proceeding.
        print('Create token: please authenticate...')
        
        while True:
            admin_username = raw_input('Enter admin username: '******'Enter admin password: '******'Please sign in using administrator credentials.')
            elif not User.users().get(username=admin_username).authenticate(admin_password):
                print("Username/password don't match.")
            else:
                break

        username = raw_input('Enter username to create a token for: ')
        user = User.users().get(username=username)
        if user:
            try:
                token = Token(user=user)
                token.save()
                print(str('Token %s created for %s' % (token.token, username)))
            except Exception as e:
                print("EXCEPTION **** %s" % e)
                print('A token already exists for %s. Doing nothing.' % username)
        else:
            print('A user with username %s does not exist.' % username)
Exemple #2
0
    def signin(self, username, password):
        db: wrappers.Collection = mongo.db.users
        result: User = deserialize_json(
            User, db.find_one({
                "username": username,
                "password": password
            }))
        if result == None:
            return ""

        tenant = result.uuid
        token_db: wrappers.Collection = mongo.db.token
        result: Token = deserialize_json(Token,
                                         token_db.find_one({"tenant": tenant}))
        t = time.time()
        if result != None:
            if result.expire_date <= t:
                xtoken = hashlib.sha1(
                    (tenant + str(t)).encode('utf-8')).hexdigest()
                result = Token(tenant, t + 7200, xtoken)
                token_db.update({"tenant": tenant}, result.__dict__)
        else:
            xtoken = hashlib.sha1(
                (tenant + str(t)).encode('utf-8')).hexdigest()
            result = Token(tenant, t + 7200, xtoken)
            token_db.insert_one(result.__dict__)

        return result.__dict__
def logar(params):
    usuario = params.get('usuario')
    email = params.get('email')
    senha = params.get('senha')
    if senha and (usuario or email):
        hash = SHA256.new()
        hash.update(senha)
        query = {'senha': hash.hexdigest()}
        if usuario:
            query['username'] = usuario
        elif email:
            query['email'] = email
        else:
            abort(403)
        u_dict = Usuario.collection().find_one(query)
        u = Usuario()
        u = Usuario.make_usuario_from_dict(u, u_dict)
        if u:
            token_dict = Token.collection().find_one({'usuario': u.get_id(), 'expired': False})
            if token_dict:
                t = Token().make_from_dict(token_dict)
                return t.token
            else:
                t = Token()
                t.token = Token.generate_token()
                t.usuario = u.get_id()
                t.expired = False
                Token.collection().insert(t.make_dict())
                return t.token
        else:
            abort(403)
    else:
        abort(500)
Exemple #4
0
def new_csrf_token():
    u = current_user()
    Token.pop_exist(user_id=u.id)
    token = str(uuid.uuid4())
    form = dict(csrf_token=token, user_id=u.id)
    t = Token.new(form)
    return t.csrf_token
    def test_valid_token_upload_superuser(self):
        token = Token()
        token.is_superuser = True

        self.assertTrue(valid_token_upload(token, "POST"))
        self.assertTrue(valid_token_upload(token, "PUT"))
        self.assertTrue(valid_token_upload(token, "GET"))
        self.assertTrue(valid_token_upload(token, "DELETE"))
    def test_validate_token_expired(self, mock_from_json):
        token = Token()
        token.expired = True

        mock_from_json.return_value = token
        validate_func = mock.Mock()

        self.assertFalse(validate_token(token, "GET", None, validate_func)[0])
Exemple #7
0
 def register_identifier(self):
     value = self.ident_buffer
     if value:
         if self.is_reserved(value):
             token = Token(value, reserved=True)
         else:
             token = Token(value)
         self.append_token_list(token)
         self.ident_buffer = ""
Exemple #8
0
 def wrapper(*args, **kwargs):
     token = request.args['token']
     u = current_user()
     t = Token.one(token=token)
     if token == t.token and t.userID == u.id:
         Token.delete(t.id)
         return f(*args, **kwargs)
     else:
         abort(401)
    def test_valid_token_upload_nornal_token(self):
        token = Token()
        token.is_upload_token = True

        self.assertTrue(valid_token_upload(token, "PUT"))
        self.assertTrue(valid_token_upload(token, "POST"))

        self.assertFalse(valid_token_upload(token, "GET"))
        self.assertFalse(valid_token_upload(token, "DELETE"))
Exemple #10
0
def new_csrf_token():
    u = current_user()
    token = str(uuid.uuid4())
    if u:
        form = dict(content=token, user_id=u.id)
    else:
        form = dict(content=token, )
    Token.new(form)
    return token
Exemple #11
0
def new_csrf_token():
    u = current_user()
    token = str(uuid.uuid4())
    form = dict(
        token=token,
        username=u.username,
    )
    Token.add(form)
    return token
Exemple #12
0
 def wrapper(*args, **kwargs):
     token = request.args['token']
     u = current_user()
     t = Token.one(csrf_token=token)
     if t.user_id == u.id:
         Token.delete(id=t.id)
         log('删除了token')
         return f(*args, **kwargs)
     else:
         abort(401)
Exemple #13
0
def test_2():
    form = {
        "code": random_string(20),
        "access_token": random_string(40),
    }
    user_id = 0
    oauth_id = 1
    Token.add(form, user_id, oauth_id)
    code = form['code']
    t = Token.find_by(code=code)
    assert t.code == form['code']
    assert t.access_token == form['access_token']
Exemple #14
0
  def post(self):
    game_id = self.request.get("game")
    voter_id = self.request.get("player")

    voter = Player.get_by_id(int(voter_id))
    game = Game.get_by_id(int(game_id))

    value = base64.urlsafe_b64encode(os.urandom(16))
    token = Token(value=value, voter=voter.key, game=game.key, used=False)
    token.put()
    url = "http://vote.ouarfc.co.uk/vote/" + value
    self.response.out.write(url)
Exemple #15
0
 def wrapper(*args, **kwargs):
     if '_csrf' in request.form:
         token = request.form['_csrf']
     else:
         token = request.args['_csrf']
     u = current_user()
     t = Token.one(content=token)
     log("verify token", t)
     if t is not None and (t.user_id is None or t.user_id == u.id):
         Token.delete(content=token)
         return f(*args, **kwargs)
     else:
         abort(401)
Exemple #16
0
  def get(self, game_id):
    game = Game.get_by_id(int(game_id))
    if not game:
      self.response.out.write("Error: invalid game ID")
      logging.error("Invalid game ID: " + str(game_id))
      return

    voters = Token.query(ndb.AND(Token.game == game.key, Token.used == True)).fetch(100)
    non_voters = Token.query(ndb.AND(Token.game == game.key, Token.used == False)).fetch(100)

    template = jinja_environment.get_template('templates/voters.html')
    params = {'voters':voters,'non_voters':non_voters,'game':game}
    self.response.out.write(template.render(params))
    def post(self):
        username, password = self.create_params()
        password_sha = hashlib.sha256(password.encode()).hexdigest()
        token = token_hex(16)

        auth = Token(user=username, password=password_sha, token=token)
        db.session.add(auth)
        db.session.commit()

        token_json = Token.serialize(auth)
        response = BasicSchema(result=token_json,
                               status_code=HTTPStatus.CREATED)
        return response.make_response(BasicResponseSchema().dump(response))
Exemple #18
0
 def on_message(self, message):
     auth_token = self.request.headers.get('authorization')
     token = Token.tokens().get(token=auth_token)
     if token and token.user:
         data = json.loads(message)
         if data['msg'] == 'update':
             self.write_message(json.dumps({'msg':'updated'}))
Exemple #19
0
 def open(self):
     auth_token = self.request.headers.get('authorization')
     token = Token.tokens().get(token=auth_token)
     if token and token.user:
         WSHandler.connections.append(self)
     else:
         self.close()
Exemple #20
0
def loadUserToken(token, object):

    try:
        candidate = Token.get(key=token)
        return candidate.user
    except Token.DoesNotExist:
        return None
Exemple #21
0
 def get(self):
     try:
         auth_token = self.request.headers.get('authorization')
         token = Token.tokens().get(token=auth_token)
         if token and token.user:
             timestamp_str = self.get_query_argument('timestamp', None, True)
             if timestamp_str != None:
                 timestamp = float(timestamp_str)
             else:
                 timestamp = -1.0
             processes = []
             for p in ProcInfo.all():
                 processes.append({'group': p.group, 'name': p.name, 'pid':p.pid, 'state': p.state,
                     'statename': p.statename, 'start': p.start, 'cpu': p.get_cpu(timestamp),
                     'mem': p.get_mem(timestamp)})
             data = {'processes': processes, 'version': ProcessUpdater.version}
         else:
             data = {'error': 'not authorized'}
     except Exception as e:
         print('Error: %s' % e)
         try:
             logger = logging.getLogger('Web Server')
             logger.error(e)
         except:
             pass
         data = {'error': e}
     self.set_header('Content-Type', 'application/json')
     self.write(json.dumps(data))
Exemple #22
0
def loadUserToken(token):
    candidate = Token.get_or_none(key=token)

    if candidate:
        return candidate.user
    else:
        return None
Exemple #23
0
    def post(self):
        token_string = self.request.get("token")
        num_votes = self.request.get("votes")

        token = Token.query(Token.value == token_string).get()
        if not token:
            return

        game = token.game.get()
        voter = token.voter.get()
        num_votes = self.request.get("votes")
        if num_votes == "1":
            votes_text = "1 vote"
        else:
            votes_text = num_votes + " votes"

        template = jinja_environment.get_template("templates/self_vote_email.txt")
        if game.team == Team.WOMEN:
            pronoun = "herself"
        else:
            pronoun = "himself"

        subject = "OUARFC: " + voter.name + " tried to give " + pronoun + " " + votes_text

        message = mail.EmailMessage(sender="OUARFC <*****@*****.**>", subject=subject)
        message.to = "*****@*****.**"
        message.body = template.render(
            {"name": voter.name, "opponent": game.opponent, "date": game.date, "pronoun": pronoun, "votes": votes_text}
        )
        message.send()
        logging.info(message.body)

        vote = SelfVote(game=game.key, voter=voter.key)
        vote.put()
Exemple #24
0
  def get(self, token_string):
    token = Token.query(Token.value == token_string).get()
    if not token:
      template = jinja_environment.get_template("templates/error.html")
      self.response.out.write(template.render({'errmsg': "invalid voting token"}))
      return
    if token.used:
      template = jinja_environment.get_template("templates/error.html")
      self.response.out.write(template.render({'errmsg': "You've already voted!"}))
      return

    voter = token.voter.get();

    game = token.game.get()
    players = ndb.get_multi(game.players)
    players.sort(key=lambda p: p.name)

    errmsg = None
    if self.request.get("err") == str(ERROR_DUPLICATE_VOTE):
      errmsg = "You can't vote for the same person twice"
    elif self.request.get("err") == str(ERROR_VOTE_FOR_SELF):
      errmsg = "You can't vote for yourself!"

    args = {'game':game, 'players':players, 'token':token.value, 'errmsg':errmsg, 'voter':voter}
    template = jinja_environment.get_template("templates/vote.html")
    self.response.out.write(template.render(args))
Exemple #25
0
def logout():
    Token(app.config['tokens_location'], 'tokens').remove(session['token'])

    session['username'] = ''
    session['token'] = ''

    return redirect(url_for('login'))
Exemple #26
0
    def deleteToken(self, args):
        self._start(args)
        print('Delete token: please authenticate...')
        
        while True:
            admin_username = raw_input('Enter admin username: '******'Enter admin password: '******'Please sign in using administrator credentials.')
            elif not User.users().get(username=admin_username).authenticate(admin_password): #Db.instance().authenticate_user(admin_username, admin_password):
                print("Username/password don't match.")
            else:
                break

        username = raw_input('Enter username for token to delete: ')
        user = User.users().get(username=username)
        if user:
            token = Token.tokens().get_token_for_user(user=user)
            if token:
                token.delete()
                print('Deleted token belonging to %s.' % username)
            else:
                print('%s has no tokens to delete.' % username)
        else:
            print('%s has no tokens to delete.' % username)
    def test_validate_token_true(self, mock_from_json):
        token = Token()

        mock_from_json.return_value = token
        validate_func = mock.Mock()
        validate_func.side_effect = [True, True]

        token.is_ip_restricted = False

        self.assertTrue(
            validate_token(token, "GET", None, validate_func)[0])

        token.is_ip_restricted = True
        token.ip_address = "127.0.0.1"

        self.assertTrue(
            validate_token(token, "GET", "127.0.0.1", validate_func)[0])
Exemple #28
0
def test_1():
    form = {
        "code": random_string(20),
        "access_token": random_string(40),
    }
    t = Token(form)
    assert t.code == form['code']
    assert t.access_token == form['access_token']
Exemple #29
0
 def get(self):
     try:
         username = self.request.headers.get('username')
         password = self.request.headers.get('password')
         user = User.users().get(username=username)
         if user.authenticate(password):
             token = Token.tokens().get_token_for_user(user)
             if not token:
                 token = Token(user=user)
                 token.save()
             data = {'token': token.token}
         else:
             data = {'error': 'invalid username/password'}
     except Exception as e:
         data = {'error': str(e)}
     self.set_header('Content-Type', 'application/json')
     self.write(json.dumps(data))
Exemple #30
0
def new_csrf_token():
    u = current_user()
    print(u.id)
    token = str(uuid.uuid4())
    form = {
        'token': token
    }
    t = Token.new(form, u.id)
    return t.token
def livros_desejo_post(params):
    usuario = Token.get_usuario_from_token(params.get('token'))
    livro = Livros.collection().find_one({'_id': ObjectId(params.get('livro'))})
    if usuario and livro:
        livro = Livros.make_livro_from_dict(Livros(), livro)
        usuario.set_livro_deseja(livro)
        return "ok"
    else:
        abort(500)
Exemple #32
0
async def login(login: Login,
                users: UserRepository = Depends(get_user_repository)):
    user = await users.get_by_email(login.email)
    if user is None or not verify_password(login.password,
                                           user.hashed_password):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="Incorrect username or password")
    return Token(access_token=create_access_token({"sub": user.email}),
                 token_type="Bearer")
Exemple #33
0
 def delete_game(self, game):
   tokens = Token.query(Token.game == game.key)
   keys = [token.key for token in tokens]
   votes = Vote.query(Vote.game == game.key)
   keys.extend([vote.key for vote in votes])
   votes = SelfVote.query(SelfVote.game == game.key)
   keys.extend([vote.key for vote in votes])
   ndb.delete_multi_async(keys)
   game.key.delete()
Exemple #34
0
 def wrapper(*args, **kwargs):
     data = request_data()
     token = data[0].get('token')
     u = current_user()
     t = Token.find_by(token=token)
     if t is not None and t.username == u.username:
         # csrf_tokens.pop(token)
         return f(*args, **kwargs)
     else:
         abort(401)
 def pop_line(self):
     expression = []
     while self.input[0].identifier != 47:
         if self.input[0].identifier == 7:
             self.input.insert(0, Token(value=';', reserved=True))
             continue
         expression.append(self.input[0])
         self.input.pop(0)
     expression.append(self.input[0])
     return expression
def livros_avaliacoes_post(params):
    usuario = Token.get_usuario_from_token(params.get('token'))
    livro = Livros.collection().find_one({'_id': ObjectId(params.get('livro'))})
    avaliacao = int(params.get('avaliacao'))
    if usuario and livro and (0 <= avaliacao <= 5):
        livro = Livros.make_livro_from_dict(Livros(), livro)
        usuario.set_avaliacao(avaliacao, livro)
        return "ok"
    else:
        abort(500)
def livros_resenhas_post(params):
    usuario = Token.get_usuario_from_token(params.get('token'))
    livro = Livros.collection().find_one({'_id': ObjectId(params.get('livro'))})
    resenha = params.get('avaliacao')
    if usuario and livro and resenha:
        livro = Livros.make_livro_from_dict(Livros(), livro)
        usuario.set_resenha(resenha, livro)
        return "ok"
    else:
        abort(500)
Exemple #38
0
 def post(self):
     data = dict()
     args = post_parser.parse_args()
     try:
         userModel = User()
         tokenModel = Token()
         deviceModel = Device()
         appVersion = AppVeriosn()
         minv, recentv = appVersion.getLatestVersion()
         user = userModel.isUserExist(args)
         if user:
             device = None
             for d in user.devices:
                 if args['device_id'] == d.device_id:
                     device = d
                     break
             if device is None:
                 token = tokenModel.createNewToken(args)
                 args['user_id'] = user.id
                 args['token_id'] = token.id
                 newDevice = deviceModel.addDevice(args)
             else:
                 device.token.updateToken(device.token.id, True, args)
                 token = device.token
             data = {"token": token.token}
             user = sqlAlchemyObjToDict(user)
             data.update(user)
         else:
             newUser = userModel.addUser(args)
             newToken = tokenModel.createNewToken(args)
             args['user_id'] = newUser.id
             args['token_id'] = newToken.id
             newDevice = deviceModel.addDevice(args)
             data = {"token": newToken.token}
             newUser = sqlAlchemyObjToDict(newUser)
             data.update(newUser)
         data['min'] = minv
         data['recent'] = recentv
         return marshal(data, resource_fields), 200
     except Exception, e:
         data['message'] = str(e)
         return data, 400
 def post(self):
     response = None
     try:
         client_id = self._get_client_id_from_request()
         client_secret = self._get_client_secret_from_request()
         response = self._create_access_token_response(
             Token.create(client_id, client_secret))
     except Exception as e:
         status_code = 403
         msg = "Cannot create tokens, invalid credentials"
         response = create_error_response(status_code, msg)
     return response
Exemple #40
0
    def decorated(*args, **kwargs):

        if 'token' in session and 'username' in session:
            token = session['token']
            username = session['username']
        else:
            return redirect(url_for('login'))

        if not Token(app.config['tokens_location'], 'tokens').validate(
                username, token, 10):
            response = {'response': render_template('relog_form.html')}
            user = User(get_db()).get_user_by_username(username)

            if user is not None:
                socketio.emit('relog', response, room=user['room'])

            return redirect(url_for('login'))

        Token(app.config['tokens_location'], 'tokens').update(token)

        return f(*args, **kwargs)
Exemple #41
0
    async def get(self, user):

        if user.is_remote:
            resp.status = falcon.HTTP_401
            resp.body = json.dumps({"Error": "Remote user"})

        token = Token.create(user=user)

        payload = {"token": "Bearer " + token.key}

        self.write(payload)
        self.set_status(200)
Exemple #42
0
def init_functions():
    import models.ast_nodes as ast
    from models import types
    from models.token import TokenType
    from models.token import Token
    from models.instructions import InstructionType

    return [
        ast.DeclFun(
            Token(TokenType.IDENTIFIER, 0, 'std', 0, value='clear_screen'), [],
            ast.AstTypePrimitive(types.Void), ast.StmntBlock([]),
            InstructionType.CLEAR_SCREEN),
        ast.DeclFun(
            Token(TokenType.IDENTIFIER, 0, 'std', 0, value='put_char_x_y'), [
                ast.FunParam(
                    ast.AstTypePrimitive(types.Char),
                    Token(TokenType.IDENTIFIER, 0, 'std', 0, value='c'),
                ),
                ast.FunParam(
                    ast.AstTypePrimitive(types.Int),
                    Token(TokenType.IDENTIFIER, 0, 'std', 0, value='x'),
                ),
                ast.FunParam(
                    ast.AstTypePrimitive(types.Int),
                    Token(TokenType.IDENTIFIER, 0, 'std', 0, value='y'),
                )
            ], ast.AstTypePrimitive(types.Void), ast.StmntBlock([]),
            InstructionType.PUT_CHAR_X_Y),
        ast.DeclFun(
            Token(TokenType.IDENTIFIER, 0, 'std', 0, value='get_input'), [
                ast.FunParam(
                    ast.AstTypePointer(
                        ast.AstTypeArray(ast.AstTypePrimitive(types.Char))),
                    Token(TokenType.IDENTIFIER, 0, 'std', 0, value='buff'),
                )
            ], ast.AstTypePrimitive(types.Int), ast.StmntBlock([]),
            InstructionType.GET_INPUT),
        ast.DeclFun(Token(TokenType.IDENTIFIER, 0, 'std', 0, value='sleep'), [
            ast.FunParam(
                ast.AstTypePrimitive(types.Int),
                Token(TokenType.IDENTIFIER, 0, 'std', 0, value='ms'),
            )
        ], ast.AstTypePrimitive(types.Void), ast.StmntBlock([]),
                    InstructionType.SLEEP)
    ]
Exemple #43
0
 def f():
     log('oauth_required')
     authorization = request.headers.get('Authorization')
     access_token = authorization[6:]
     token = Token.find_by(access_token=access_token)
     user_id = token.user_id
     user = User.find_by(id=user_id)
     if user == None:
         log('未授权')
         return redirect(url_for('user.login_view'))
     else:
         log('已授权用户', route_function)
         return route_function(user)
Exemple #44
0
    def on_get(self, req, resp):
        user = req.context['user']

        if user.remote:
            resp.status = falcon.HTTP_401
            resp.body = json.dumps({"Error": "Remote user"})

        token = Token.create(user=user)

        payload = {"token": token.key}

        resp.status = falcon.HTTP_200
        resp.body = json.dumps({"token": auth_backend.get_auth_token(payload)})
Exemple #45
0
def update():
    tokens = Token.all()
    pwd = request.form['password']
    for t in tokens:
        if t.token != '':
            user_id = int(t.user_id)
            sorted_pwd = User.salted_password(pwd)
            User.update(user_id, password=sorted_pwd)
            result = '重置密码成功'
            return render_template('login.html', result=result)
        else:
            result = '重置密码失败'
            return render_template('login.html', result=result)
Exemple #46
0
    def listTokens(self, args):
        self._start(args)

        print("%s%sCreated" % ("Username".ljust(40), "Token".ljust(42)))
        try:
            # We need to put this in a try block because it's possible that the users
            # table won't exist if there hasn't been a user created. The 'all()' function
            # relies on a join query with users.

            # This will be fixed once I implement migrations
            for token in Token.tokens().all():
                print("%s%s%s" % (token.user.username.ljust(40), token.token.ljust(42),
                    datetime.fromtimestamp(token.created).strftime('%d-%m-%Y %H:%M:%S')))
        except:
            pass
Exemple #47
0
def callback():
    """
    Step 2 of OAuth2 process. This callback is requested by the HubSpot Api on the redirect response.

    The token can now be fetched using the code provided on the redirect call received.

    Once the token is persisted, the redirect for deals endpoint is returned
    """
    code = request.values.get("code")
    token = HubSpotApi.fetch_token(code=code, auth_resp_url=request.url, auth_callback_url=AUTH_REDIRECT_URL)
    try:
        Token(**token).save()
    except Exception:
        logger.exception('Error storing new token')
        abort(500)
    return redirect(url_for('.deals'))
def refresh_token():
    """
    Refresh access token
    """
    global token
    data = {
        "grant_type": "refresh_token",
        "client_id": KeycloakConfig.CLIENT_ID,
        "refresh_token": token.refresh,
        "scope": "email profile openid",
        "client_secret": KeycloakConfig.CLIENT_SECRET
    }
    response = requests.post(KeycloakConfig.TOKEN_URI, data)
    response.raise_for_status()
    raw_json = response.json()
    token = Token(raw_json["access_token"], raw_json["refresh_token"])
Exemple #49
0
    def on_post(self, req, resp):
        user = req.context['user']

        token = req.get_param('token').replace('Bearer', '').split(' ')[-1]
        if user.remote:
            resp.status = falcon.HTTP_404
            resp.body = json.dumps({"Error": "Remote user"})

        token = Token.get(Token.key == token)

        if user == token.user:
            token.delete_instance()
            resp.status = falcon.HTTP_200
            resp.body = json.dumps({"Success": "Removed token"})
        else:
            resp.status = falcon.HTTP_401
            resp.body = json.dumps({"Error": "Unauthorized user"})
Exemple #50
0
 def add_token(self,
               token_type: TokenType,
               line_number=None,
               rollback=False,
               keep_state=False,
               with_value=True,
               keep_buffer=False):
     self.tokens.append(
         Token(token_type, line_number if line_number else self.line_number,
               self.file_name, self.offset_in_line,
               self.token_buffer if with_value else ''))
     if not keep_buffer:
         self.token_buffer = ''
     if not keep_state:
         self.state = LexingState.START
     if rollback:
         self.offset -= 1
         self.offset_in_line -= 1
Exemple #51
0
  def post(self):
    token_string = self.request.get("token")
    token = Token.query(Token.value == token_string).get()
    if not token:
      template = jinja_environment.get_template("templates/error.html")
      self.response.out.write(template.render({'errmsg': "invalid voting token"}))
      return
    if token.used:
      template = jinja_environment.get_template("templates/error.html")
      self.response.out.write(template.render({'errmsg': "You've already voted!"}))
      return

    game = token.game
    voter = token.voter

    three = self.request.get("three")
    two = self.request.get("two")
    one = self.request.get("one")

    if one in [two, three] or two == three:
      return self.redirect("/vote/" + token.value + "?err=" + str(ERROR_DUPLICATE_VOTE))

    if str(voter.id()) in [one, two, three]:
      return self.redirect("/vote/" + token.value + "?err=" + str(ERROR_VOTE_FOR_SELF))

    three_player = Player.get_by_id(int(three))
    two_player = Player.get_by_id(int(two))
    one_player = Player.get_by_id(int(one))

    vote = Vote(game=game, three=three_player.key, two=two_player.key, one=one_player.key)
    token.used = True

    vote.put()
    token.put()

    template = jinja_environment.get_template('templates/success.html')
    self.response.out.write(template.render({}))
 def validate():
     params = get_params(request)
     if Token.validate_token(params.get('token')):
         return func()
     else:
         abort(403)
Exemple #53
0
    def post(self):
        player_id = self.request.get("player")
        game_id = self.request.get("game")

        player = Player.get_by_id(int(player_id))
        game = Game.get_by_id(int(game_id))

        token = Token.query(ndb.AND(Token.game == game.key, Token.voter == player.key)).get()

        if not token:
            logging.info("No token found for %s. Creating new token.", player.name)
            token_string = base64.urlsafe_b64encode(os.urandom(16))
            token = Token(value=token_string, voter=player.key, game=game.key, used=False)
            token.put()
        else:
            logging.info("Token found for %s.", player.name)
            if token.used:
                logging.info("%s has already voted, not sending email.", player.name)
                return

        url = "http://vote.ouarfc.co.uk/vote/" + token.value

        if player.phone:
            logging.info("Sending SMS to %s", player.name)
            template = jinja_environment.get_template("templates/sms.txt")
            sms_data = {
                "ORIGINATOR": "OUARFC",
                "NUMBERS": player.phone,
                "BODY": template.render({"url": url, "opponent": game.opponent, "team": Team.getString(game.team)}),
            }

            response = urlfetch.fetch(
                "https://api.zensend.io/v3/sendsms",
                payload=urllib.urlencode(sms_data),
                method=urlfetch.POST,
                headers={"X-API-KEY": config.zensend_key},
            )
            content_type = response.headers["content-type"]
            if content_type is not None and "application/json" in content_type:
                result = json.loads(response.content)
                if "success" in result:
                    logging.info("Successfully sent SMS to " + player.phone)
                    if config.phone_only:
                        # SMS was a success, don't send email
                        return
                elif "failure" in result:
                    failure = result["failure"]
                    logging.error(
                        "SMS send failed. Player: %s, phone: %s, parameter: %s, error code: %s, status code: %s",
                        player.name,
                        player.phone,
                        failure["parameter"],
                        failure["failcode"],
                        response.status_code,
                    )
                else:
                    logging.error("SMS send failed. Status code: %s", response.status_code)
            else:
                logging.error("SMS send failed. Status code: %s", response.status_code)

        template = jinja_environment.get_template("templates/email.txt")
        subject = "OUARFC: Please Vote For Best & Fairest"
        message = mail.EmailMessage(sender="OUARFC <*****@*****.**>", subject=subject)
        message.to = player.email
        message.body = template.render(
            {
                "name": player.name,
                "opponent": game.opponent,
                "date": game.date,
                "team": Team.getString(game.team),
                "url": url,
            }
        )
        logging.info("Sending email to " + player.email)
        message.send()
        logging.info(message.body)
    def test_token_expires_expired(self):
        token = Token()
        token.expires_on = "1970-01-01"

        self.assertIsInstance(token.expires_on, datetime.datetime)
        self.assertTrue(_is_expired_token(token))
def livros_avaliacoes_get(params):
    usuario = Token.get_usuario_from_token(params.get('token'))
    avaliacoes = usuario.get_livros_avaliados()
    return JSONEncoder().encode(avaliacoes)
def livros_desejo_get(params):
    usuario = Token.get_usuario_from_token(params.get('token'))
    livros = Livros.make_dict_from_livro(None, usuario.get_livros_desejo(), many=True)
    return JSONEncoder().encode(livros)
    def test_token_expires_not_expired(self):
        token = Token()
        token.expires_on = "2300-01-01"

        self.assertIsInstance(token.expires_on, datetime.datetime)
        self.assertFalse(_is_expired_token(token))
def livros_resenhas_get(params):
    usuario = Token.get_usuario_from_token(params.get('token'))
    resenhas = usuario.get_livros_resenhados()
    return JSONEncoder().encode(resenhas)
    def test_token_expires_is_expired(self):
        token = Token()
        token.expired = True

        self.assertTrue(_is_expired_token(token))
    def test_token_expires_is_not_expired(self):
        token = Token()
        token.expired = False

        self.assertFalse(_is_expired_token(token))