Example #1
0
def authorize(user, auth_request, redirect_uri):
    """
    handler with validation for the request providing a code that the client
    can use to authorize

    user param supplied by login_required
    auth_request and redirect_uri wrapper objects supplied by validate_auth_request

    NOTE: upon login the user has implicitly given permission for the neuaer
          client to obtain an authorization token with the code provided here
    """
    # store the authorization associated with this user
    # for reconciliation upon token request
    auth = Authorization(authorizer=user,

                         # generate a code for the client to submit when
                         # requesting an authorization token
                         code=str(uuid1()),

                         # an absence of the client_id should be caught in
                         # the validations above
                         client_id=auth_request.raw_args.get("client_id"),

                         # per the oauth 2 standard the redirect uri must
                         # be matched on the later request for a token
                         redirect_uri=redirect_uri.get_url())

    # gae db save
    auth.put()

    # add the unique code to the query params, and redirect to the redirect_uri
    return redirect_with_params(redirect_uri, code=auth.code)
Example #2
0
def token(token_req):
    """
    handler to convert a code into an authorization token

    token_req provided by validate_token_request decorator

    once neuaer recieves the code provided in the authorize method it will
    contact the app here where the code can be 'redeemed' for an authorization
    token
    """

    # get the stored authorization using the code and request uri
    auth = Authorization.get_with_auth(code=token_req.raw_args.get('code'),
                                       uri=token_req.raw_args.get('redirect_uri'))

    # if there were no matches report
    if not auth:
        return jsonify(**token_error_responses('no_match'))

    # if the access token has already been granted for this uri and code
    if auth.access_token:
        return jsonify(**token_error_responses('already_granted'))

    # return the access token to the requester
    return jsonify(access_token=auth.generate_token())
Example #3
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    useremail = session['email']
    authorizationindb = Authorization.query.with_entities(
        Authorization.project_key,
        Authorization.api_key).filter_by(email=useremail).first()

    if authorizationindb != None:
        return redirect(url_for('verify'))

    authoform = AuthorizationForm()

    if request.method == 'POST':
        if authoform.validate() == False:
            flash('Not valid form')
            return render_template('home.html', form=authoform)
        else:
            # get the project and API key
            email = session['email']

            # save the keys into database
            newautho = Authorization(email, authoform.client_ID.data,
                                     authoform.client_secret.data)
            db.session.add(newautho)
            db.session.commit()

            return redirect(url_for('verify'))

    elif request.method == 'GET':
        return render_template("home.html", form=authoform)
Example #4
0
def authorize(referrer):
    if not users.get_current_user():
        return login(referrer)
    else:
        cache_key='{0}/authorizations'.format(request.referrer)
        auth=cache.get(cache_key)
        email=db.Email(users.get_current_user().email())
        if auth is None:
            auth=Authorization.get_by_key_name(request.referrer)
            if auth is not None:
                cache.set(cache_key, auth)
        try:
            a=auth.approved.index(email)
        except ValueError:
            a=-1
        if a <> -1:
            return logout(referrer)
        else:
            try:
                p=auth.pending.index(email)
            except ValueError:
                p=-1
            if p <> -1:
                return pending_logout(referrer)
            else:
                try:
                    r=auth.rejected.index(email)
                except ValueError:
                    r=-1
                if r <> -1:
                    return rejected_logout(referrer)
            return authorize_logout(referrer)
Example #5
0
def reject_ticket(referrer, email):
    auth=Authorization.get_by_key_name(referrer)
    auth.pending.remove(email)
    auth.rejected.append(email)
    auth.put()
    cache_key='{0}/authorizations'.format(referrer)
    cache.set(cache_key, auth)
Example #6
0
def read_tickets():
    pending=[]
    i=0
    q=Authorization.gql("WHERE pending != Null")
    for a in q:
        i += 1
        for p in a.pending:
            pending.append({'id' : i, 'referrer' : a.key().name(), 'email' : p})
    return current_app.response_class(json.dumps(pending, indent=None if request.is_xhr else 2), mimetype='application/json')
Example #7
0
def authorization_request(referrer):
    if not users.get_current_user():
        return login(referrer)
    else:
        email=db.Email(users.get_current_user().email())
        ar=AuthRequest(referrer=referrer, email=email)
        ar.put()
        auth=Authorization.get_by_key_name(request.referrer)
        auth.pending.append(email)
        auth.put()
        return pending_logout(referrer)
Example #8
0
    def get(self):
        ip = self.request.remote_addr
        auth = Authorization.all().filter('ip = ', ip).get()

        if not auth:
            data = dict(client_id=CLIENT_ID, response_type='code')
            url = "https://banters.com/oauth/authorize?%s" % urlencode(data)
            self.redirect(url)
            return
        
        # Retrieve data about the current user
        data = dict(oauth_token=auth.token)
        url = "https://banters.com/oauth/me.json?%s" % urlencode(data)
        resp, content = Http().request(url, "GET")
        data = json.loads(content)
        
        path = os.path.join(os.path.dirname(__file__), '../html/index.html')
        self.response.out.write(template.render(path, {
            'username': data["username"],
            'avatar': data["profile_photo"]["small"]
        }))
Example #9
0
def populate_auths():
    auth_map = {
        'Woodshop': 416232,
        'Metalshop': 416231,
        'Forge': 420386,
        'LaserCutter': 416230,
        'Mig welding': 420387,
        'Tig welding': 420388,
        'Stick welding': 420389,
        'Manual mill': 420390,
        'Plasma': 420391,
        'Metal lathes': 420392,
        'CNC Plasma': 420393,
        'Intro Tormach': 420394,
        'Full Tormach': 420395
    }

    for auth in auth_map:
        if not Authorization.query.filter_by(name=auth).first():
            print(f"Adding new authorization: {auth}")
            a = Authorization(name=auth, wa_group_id=auth_map[auth])
            db.session.add(a)
            db.session.commit()
Example #10
0
    def decorated_view(*args, **kwargs):
        # validate that the json exists and is valid
        try:
            if not request.json:
                return jsonify(**error_responses_all('json_invalid'))
        except JSONDecodeError:
            return jsonify(**error_responses_all('json_invalid'))

        # validate that token exists
        token = request.json.get('access_token', None)

        if not token:
            return jsonify(**error_responses_all('access_token_missing'))

        # validate that an authorization exists matching the provided token
        # the token should have been obtained from the /authorize endpoint
        # per the oauth 2 draft spec
        auth = Authorization.get_with_token(token)

        # obviosly if there's no matching authorization break and notify
        if not auth:
            return jsonify(**error_responses_all('access_token_invalid'))

        return route(auth.authorizer, *args, **kwargs)
Example #11
0
 def decorated_view(*args, **kwargs):
     if not request.referrer:
         try:
             referrer=request.json['referrer']
         except KeyError:
             return jsonify(error='referrer missing')
     else:
         referrer=request.referrer
     cache_key='{0}/approved'.format(referrer)
     auth=cache.get(cache_key)
     email=db.Email(users.get_current_user().email())
     if users.is_current_user_admin():
         if auth is None:
             auth=Authorization.get_by_key_name(referrer)
             if auth is None:
                 auth=Authorization(key_name=referrer)
                 auth.put()
         try:
             i=auth.approved.index(email)
         except ValueError:
             i=-1
         if i==-1:
             auth.approved.append(email)
             auth.put()
         cache.set(cache_key, auth)
         return func(*args, **kwargs)
     if auth is None:
         auth=Authorization.get_by_key_name(referrer)
         if auth is not None:
             cache.set(cache_key, auth)
     try:
         i=auth.approved.index(email)
     except ValueError:
         i=-1
     if i <> -1:
         return func(*args, **kwargs)
     return jsonify(error='not authorized')
Example #12
0
def auth(request):
	from models import Authorization

	verifier = request.GET['oauth_verifier']
	req_token = request.session['req_token']

	oauth = create_oauth()
	acc_token = oauth.access_token(req_token, verifier)

	try:
		auth = Authorization.objects.get(user_id = acc_token['user_id'])
	except Authorization.DoesNotExist:
		auth = Authorization(user_id = acc_token['user_id'])
	
	auth.screen_name = acc_token['screen_name']
	auth.token = acc_token['oauth_token']
	auth.token_secret = acc_token['oauth_token_secret']
	auth.save()

	del request.session['req_token']

	request.session['user_id'] = auth.user_id

	return HttpResponseRedirect('/')