Example #1
0
 def createAccessToken(self, SESSION):
     '''
     Creates an access token for this client.
     '''
     token = gen_salt(25)
     secret = gen_salt(25)
     return AccessToken(self, self.user, token, secret, self._realms)    
 def __init__(self, user, redirect_uris, realms, client_key=None, client_secret=None):
     assert isinstance(user, User), "user = {!r}, of type {}".format(user, type(user))
     self.user = user
     self.redirect_uris = redirect_uris
     self.client_key = client_key or gen_salt(30)
     self.client_secret = client_secret or gen_salt(40)
     self.realms = list(realms)
Example #3
0
def test_auth():
    """
    A route for authenticating a user (OAuth), for testing.
    """
    user_id = request.form['id']

    client = Client(
        client_id=gen_salt(40),
        client_secret=gen_salt(50),
        _redirect_uris='http://localhost:5000/authorized',
        _default_scopes='userinfo',
        _allowed_grant_types='authorization_code refresh_token',
        user_id=user_id,
    )
    db.session.add(client)

    token = Token(
        access_token=gen_salt(40),
        refresh_token=gen_salt(40),
        token_type='authorization_code',
        _scopes='userinfo',
        expires=datetime.max,
        client_id=client.client_id,
        user_id=user_id
    )
    db.session.add(token)
    db.session.commit()
    return jsonify(token=token.access_token)
Example #4
0
def add_client():
    if request.method == 'POST':
        user = current_user()
        scopes = 'general'

        if user['authority'] == 'Admin':
            scopes = 'general inhabitant admin'
        elif user['authority'] == 'Inhabitant':
            scopes = 'general inhabitant'

        client = Client(
            name = request.form['name'],
            client_id = gen_salt(40),
            client_secret = gen_salt(50),
            user_id = current_user()['id'],
            raw_redirect_uris = request.form['redirect_uri'],
            raw_default_scopes=scopes,
        )

        db.session.add(client)
        db.session.commit()
    else:
        return render_template('add_client.html')

    return redirect(url_for('clients'))
Example #5
0
def challenge():
  uuid = request.args.get('uuid')
  session = ws.hashlib.sha256(SESSION_SECRET + uuid).hexdigest()
  session_challenge = session + "_challenge"
  session_pow_challenge = session + "_pow_challenge"

  if session_pow_challenge in session_store:
    session_store.delete(session_pow_challenge)

  if session_challenge in session_store:
    session_store.delete(session_challenge)

  salt = ws.hashlib.sha256(SERVER_SECRET + uuid).hexdigest()
  pow_challenge = ws.gen_salt(32)
  challenge = ws.gen_salt(32)

  session_store.put(session_pow_challenge, pow_challenge)
  session_store.put(session_challenge, challenge)
  print session_challenge
  response = {
      'salt': salt,
      'pow_challenge': pow_challenge,
      'challenge': challenge
  }

  return jsonify(response)
Example #6
0
def challenge():
  validate_uuid = UUID(request.args.get('uuid'))
  uuid = str(validate_uuid)
  session = ws.hashlib.sha256(config.SESSION_SECRET + uuid).hexdigest()
  salt = ws.hashlib.sha256(config.SERVER_SECRET + uuid).hexdigest()
  pow_challenge = ws.gen_salt(32)
  challenge = ws.gen_salt(32)

  if config.LOCALDEVBYPASSDB:
    session_challenge = session + "_challenge"
    session_pow_challenge = session + "_pow_challenge"

    if session_pow_challenge in session_store:
      session_store.delete(session_pow_challenge)

    if session_challenge in session_store:
      session_store.delete(session_challenge)

    session_store.put(session_pow_challenge, pow_challenge)
    session_store.put(session_challenge, challenge)
  else:
    dbExecute("with upsert as (update sessions set challenge=%s, pchallenge=%s, timestamp=DEFAULT where sessionid=%s returning *) "
              "insert into sessions (sessionid, challenge, pchallenge) select %s,%s,%s where not exists (select * from upsert)", 
              (challenge, pow_challenge, session, session, challenge, pow_challenge))
    dbCommit()
    
  response = {
      'salt': salt,
      'pow_challenge': pow_challenge,
      'challenge': challenge
  }

  return jsonify(response)
Example #7
0
def client():
    user = current_user()
    if not user:
        # session['id'] = 1  # temporary decision
        return redirect(url_for('register'))

    item = Client(
        client_id=gen_salt(40),
        client_secret=gen_salt(50),
        _redirect_uris=' '.join([
            '%s/%s' % (settings.BASE_URL, 'authorized'),
            'http://localhost:8000/authorized',
            'http://127.0.0.1:8000/authorized',
            'http://127.0.1:8000/authorized',
            'http://127.1:8000/authorized',
            ]),
        _default_scopes='email',
        user_id=session['id'],
    )

    db.session.add(item)
    db.session.commit()

    return jsonify(
        client_id=item.client_id,
        client_secret=item.client_secret,
    )
Example #8
0
def register():
    current_user = User.getCurrentUser()
    if current_user is None:
        return redirect(url_for('frontend.index'))

    if request.method == 'GET':
        return render_template('app/register.html')

    elif request.method == 'POST':
        req_fields = ['name', 'host_url', 'redirect_uris', 'scopes']
        for field in req_fields:
            if not request.form.get(field):
                abort(404)

        new_app = Client(
            id=gen_salt(40),
            client_secret=gen_salt(50),
            name=request.form.get('name'),
            description=request.form.get('desc'),
            user_id=current_user.id,
            _host_url=request.form.get('host_url'),
            _redirect_uris=urlnorm(request.form.get('redirect_uris')),
            _default_scopes=' '.join(request.form.get('scopes').split(',')),
            _is_private=False
        )
        new_app.persist()

        return redirect(url_for('user.myApps'))
Example #9
0
def register():
	logger.debug(" in register session[id] is %s", session['id'])
	user = current_user()
	
	if request.method == 'GET':
		return render_template('register.html', user=user)
	if request.method == 'POST':
		applicationName = request.form.get('applicationName')
		applicationUrl = request.form.get('applicationUrl')
		applcationDescription=request.form.get('applcationDescription')
		applicationCallbackUrl=request.form.get('applicationCallbackUrl')
		userId=request.form.get('userId')
		item = Client(
        client_id=gen_salt(40),
        client_secret=gen_salt(50),
        application_name=applicationName,
        application_url=applicationUrl,
        _redirect_uris=' '.join([
        	applicationCallbackUrl,
            ]),
        _default_scopes='email',
        user_id=userId,
    	)
		from pprint import pprint
		pprint (vars(item))
        db.session.add(item)
        db.session.commit()
        
    	return jsonify(
        client_id=item.client_id,
        client_secret=item.client_secret,
        )
Example #10
0
    def get(self, *args, **kwargs):
        user = self.current_user()

        if not user:
            return self.redirect_view('home')

        client = models.Client(
            client_id=gen_salt(40),
            client_secret=gen_salt(50),
            _redirect_uris=' '.join([
                'http://localhost:8000/authorized/',
                'http://127.0.0.1:8000/authorized/',
                'http://127.0.1:8000/authorized/',
                'http://127.1:8000/authorized/',
            ]),
            _default_scopes='email',
            user_id=user.id,
        )

        db.session.add(client)
        db.session.commit()

        return self.jsonify({
            'client_id': client.client_id,
            'client_secret': client.client_secret,
        })
def client():
    """
    This endpoint creates and provides the authenticated user with
    ``client_id`` and ``client_secret``.
    """
    if not current_user.is_authenticated:
        return api.abort(code=http_exceptions.Unauthorized.code)
    # XXX: remove hard-codings
    # TODO: reconsider using gen_salt
    # TODO: develop sensible scopes
    # TODO: consider moving `db` operations into OAuth2Client class implementation
    client_instance = OAuth2Client(
        client_id=security.gen_salt(40),
        client_secret=security.gen_salt(50),
        _redirect_uris=" ".join(
            [
                "http://localhost:8000/authorized",
                "http://127.0.0.1:8000/authorized",
                "http://127.0.0.1:5000/api/v1/o2c.html",
                "http://127.0.0.2:8000/authorized",
                "http://127.0.1:8000/authorized",
                "http://127.1:8000/authorized",
            ]
        ),
        _default_scopes="users:read users:write email",
        user_id=current_user.id,
    )
    db.session.add(client_instance)
    db.session.commit()
    return jsonify(client_id=client_instance.client_id, client_secret=client_instance.client_secret)
Example #12
0
 def generate_api_token(self):
     token = security.gen_salt(40)
     while Account.query.filter_by(api_token=token).count():
         token = security.gen_salt(40)
     self.api_token = token
     self.save()
     return self
Example #13
0
def sample_client():
    # Adding sample client credentials to Database
    client_id = gen_salt(40)
    client_secret = gen_salt(50)
    test_client = Client(client_id=client_id, client_secret=client_secret)
    db.session.add(test_client)
    db.session.commit()
    return test_client
Example #14
0
def client():
    item = Client(client_id=gen_salt(40),
                  client_secret=gen_salt(50),
                  _redirect_uris='/',
                  is_confidential=True)
    db.session.add(item)
    db.session.commit()
    return make_response(json.dumps(item.dict()), 200)
Example #15
0
def candidate_same_domain(user_same_domain):
    """
    Fixture adds candidate for user_same_domain
    """
    candidate = Candidate(last_name=gen_salt(20),
                          first_name=gen_salt(20),
                          user_id=user_same_domain.id)
    Candidate.save(candidate)
    return candidate
Example #16
0
def user_second_candidate(user_second):
    """
    Fixture adds candidate for user_second
    """
    candidate = Candidate(last_name=gen_salt(20),
                          first_name=gen_salt(20),
                          user_id=user_second.id)
    Candidate.save(candidate)
    return candidate
Example #17
0
    def bootstrap_user():
        """
        Return or create a OAuthClient owned by the authenticated real user.
        Re-uses an existing client if "oauth_client" is found in the database
        for this user, otherwise writes a new client to the database.

        Similar logic performed for the OAuthToken.

        :return: OAuthToken instance
        """
        assert current_user.email != current_app.config['BOOTSTRAP_USER_EMAIL']

        uid = current_user.get_id()
        client_name = current_app.config.get('BOOTSTRAP_CLIENT_NAME', 'BB client')

        client = OAuthClient.query.filter_by(
            user_id=uid,
            name=client_name,
        ).first()

        if client is None:
            scopes = ' '.join(current_app.config['USER_DEFAULT_SCOPES'])
            salt_length = current_app.config.get('OAUTH2_CLIENT_ID_SALT_LEN', 40)
            client = OAuthClient(
                user_id=current_user.get_id(),
                name=client_name,
                description=client_name,
                is_confidential=True,
                is_internal=True,
                _default_scopes=scopes,
            )
            client.gen_salt()
            db.session.add(client)

            token = OAuthToken(
                client_id=client.client_id,
                user_id=uid,
                access_token=gen_salt(salt_length),
                refresh_token=gen_salt(salt_length),
                expires=datetime.datetime(2500, 1, 1),
                _scopes=scopes,
                is_personal=False,
                is_internal=True,
            )
            db.session.add(token)
            db.session.commit()
            current_app.logger.info(
                "Created BB client for {email}".format(email=current_user.email)
            )
        else:
            token = OAuthToken.query.filter_by(
                client_id=client.client_id,
                user_id=current_user.get_id(),
            ).first()

        return client, token
Example #18
0
def client():
    item = Client(
            client_id=gen_salt(40),
            client_secret=gen_salt(50),
            _redirect_uris='/',
            is_confidential=True
    )
    db.session.add(item)
    db.session.commit()
    return make_response(json.dumps(item.dict()), 200)
def login(provider):
    if provider == "dgfr":
        remote_app = dgfr
    else:
        abort(400, 'Unknown login provider')
    return remote_app.authorize(
        callback=url_for('authorized', provider=provider, _external=True),
        state=security.gen_salt(10),
        nonce=security.gen_salt(10),
    )
Example #20
0
def candidate_second(user_first):
    """
    Fixture adds candidate for user_first
    """
    candidate = Candidate(last_name=gen_salt(20),
                          first_name=gen_salt(20),
                          user_id=user_first.id)
    db.session.add(candidate)
    db.session.commit()
    return candidate
Example #21
0
 def get_authorized_header(self, user_id=1, scope=""):
     # prepare token
     token = OAuthToken(
         access_token=gen_salt(10), refresh_token=gen_salt(10), token_type="Bearer", scope=scope, expires_in=3600
     )
     token.user_id = user_id
     token.client_id = 1
     db.session.add(token)
     db.session.commit()
     return {"Authorization": "Bearer %s" % token.access_token, "Content-Type": "application/json"}
Example #22
0
 def on_model_change(self, form, model, is_created):
     if is_created:
         model.client_id = gen_salt(24)
         if model.token_endpoint_auth_method == 'none':
             model.client_secret = ''
         else:
             model.client_secret = gen_salt(48)
         user = current_user()
         if user:
             model.user_id = user.id
Example #23
0
    def generate(redirect_uris):

        item = Client(
            client_id=gen_salt(40),
            client_secret=gen_salt(50),
            _redirect_uris=" ".join(redirect_uris),
            _default_scopes="email",
            user_id=None,
        )
        item.save()
Example #24
0
 def create(cls, name, redirect_uris, default_scopes):
     client = cls(
         name=name,
         client_id=gen_salt(40),
         client_secret=gen_salt(60),
         _redirect_uris=' '.join(redirect_uris),
         _default_scopes=' '.join(default_scopes)
     )
     db.session.add(client)
     db.session.commit()
     return client
Example #25
0
 def create_user(self, username=None):
     username = username or gen_salt(6)
     user = User()
     user.douban_uid = username
     user.douban_name = username
     user.douban_id = random.randint(1, 1000)
     user.douban_access_token = gen_salt(32)
     user.douban_refresh_token = gen_salt(32)
     db.session.add(user)
     db.session.commit()
     return user
Example #26
0
def client():
    user = current_user()
    if not user:
        return redirect('/')
    item = Client(client_id=gen_salt(40),
                  client_secret=gen_salt(50),
                  user_id=user.id,
                  _scopes="access")
    db.session.add(item)
    db.session.commit()
    return jsonify(client_id=item.client_key, client_secret=item.client_secret)
Example #27
0
def candidate_first(user_first):
    """
    Fixture will create a candidate in user_first's domain
    :rtype: Candidate
    """
    candidate = Candidate(last_name=gen_salt(20),
                          first_name=gen_salt(20),
                          user_id=user_first.id)
    db.session.add(candidate)
    db.session.commit()
    return candidate
Example #28
0
def create_client_credentials(client, persist_to_db=True):
    client.client_id=gen_salt(40)
    client.client_secret=gen_salt(50)
    
    if persist_to_db:
        client._default_scopes='email'
        client.user_id=1
        db.session.add(client)
        db.session.commit()

    return client
Example #29
0
def oidc_create_client():
    """Endpoint for processing OpenID Connect client

    When the api is accessed using GET HTTP method, a form is returned to ask for
    client's registration information.

    When the api is accessed using POST HTTP method, the client's information is
    gathered and a corresponding 'client' entry is registered in the provider's
    database
    """
    oauth_client_form = OAuthClientRegisterForm(request.form)

    def split_by_crlf(s):
        """
        Helper function to splitlives for the input
        """
        return [v for v in s.splitlines() if v]

    if request.method == 'POST' and oauth_client_form.validate():
        client_id = gen_salt(24)
        client = OAuth2Client(client_id=client_id,
                              scope=oauth_client_form.scope.data
                              )  # optionally bind a user with the client
        client.client_id_issued_at = int(time.time())
        if oauth_client_form.token_endpoint_auth_method.data == 'none':
            client.client_secret = ''
        else:
            client.client_secret = gen_salt(48)

        client_metadata = {
            "client_name":
            oauth_client_form.client_name.data,
            "client_uri":
            oauth_client_form.client_uri.data,
            "grant_types":
            split_by_crlf(oauth_client_form.grant_type.data),
            "redirect_uris":
            split_by_crlf(oauth_client_form.redirect_uri.data),
            "response_types":
            split_by_crlf(oauth_client_form.response_type.data),
            "scope":
            oauth_client_form.scope.data,
            "token_endpoint_auth_method":
            oauth_client_form.token_endpoint_auth_method.data
        }
        client.set_client_metadata(client_metadata)

        auth_db.session.add(client)
        auth_db.session.commit()
        return redirect(url_for('auth.oauth_list'))

    return render_template('/auth/oidc_create_client.html',
                           form=oauth_client_form)
Example #30
0
def reset_api_key():
    client = Client.query.filter_by(client_id=request.form['id']).first()
    if client is None:
        return ('ID Not Found', 500)

    client.client_id = gen_salt(40)
    client.client_secret = gen_salt(50)

    db.session.add(client)
    db.session.commit()

    return redirect(url_for('clients'))
Example #31
0
 def __init__(self, name, description, user, realms, redirect_uris, instance):
     '''
     Constructor
     '''
     self.name = name
     self.description = description
     self.user = user
     self.client_key = gen_salt(25)
     self.client_secret = gen_salt(25)
     self._realms = " ".join(realms)
     self._redirect_uris = " ".join(redirect_uris)
     self.instance = instance
Example #32
0
def oauth_client(user):
    data = {
        "id": str(uuid4()).replace('-', ''),
        "user_id": user.id,
        "client_id": gen_salt(24),
        "client_secret": gen_salt(48)
    }
    oauth_client = OAuth2Client(**data)

    db.session.add(oauth_client)

    return oauth_client
Example #33
0
def connect_redis():
    if 'csrf' not in session:
        session['csrf'] = '{}:0'.format(gen_salt(12))
    else:
        csrf = session.get('csrf')
        try:
            token, uses = csrf.split(':', 1)
        except:
            session.pop('csrf')
        else:
            if int(uses) >= 10:
                session['csrf'] = '{}:0'.format(gen_salt(12))
    g.redis = redis.Redis()
def connect_redis():
    if 'csrf' not in session:
        session['csrf'] = '{}:0'.format(gen_salt(12))
    else:
        csrf = session.get('csrf')
        try:
            token, uses = csrf.split(':', 1)
        except:
            session.pop('csrf')
        else:
            if int(uses) >= 10:
                session['csrf'] = '{}:0'.format(gen_salt(12))
    g.redis = redis.Redis()
Example #35
0
    def __init__(self, name, id_=None):
        """ Create new (volatile) user object

        :param name: str
        :param id_: str
        :return:
        """
        if id_ is None:
            id_ = gen_salt(40)
            while id_ in users:
                id_ = gen_salt(40)
        self.id = id_
        self.name = name
Example #36
0
def create_client():
    client = Client(
        client_id=gen_salt(40),
        client_secret=gen_salt(50),
        _redirect_uris='http://localhost:5000/authorized',
        _default_scopes='userinfo',
        _allowed_grant_types='authorization_code refresh_token password',
        user_id=None,
        is_confidential=True # make a confidential client.
    )
    db.session.add(client)
    db.session.commit()
    print("client id: {0}\nclient secret: {1}".format(client.client_id, client.client_secret))
Example #37
0
def create_client():
    form = ClientForm(request.form)
    if form.validate():
        user = current_user()
        client = form.to_client()
        client.user_id = user.id
        client.grant_types = GRANT_TYPES
        client.response_types = RESPONSE_TYPES
        client.client_id = gen_salt(24)
        client.client_secret = gen_salt(48)
        db.session.add(client)
        db.session.commit()
    return redirect(url_for('front.home'))
 def __init__(self,
              user,
              redirect_uris,
              realms,
              client_key=None,
              client_secret=None):
     assert isinstance(user, User), "user = {!r}, of type {}".format(
         user, type(user))
     self.user = user
     self.redirect_uris = redirect_uris
     self.client_key = client_key or gen_salt(30)
     self.client_secret = client_secret or gen_salt(40)
     self.realms = list(realms)
Example #39
0
def add(user):
    form = ClientAdd(request.form or None)

    if not request.form:
        return render_template(
            "oidc/admin/client_add.html", form=form, menuitem="admin"
        )

    if not form.validate():
        flash(
            _("The client has not been added. Please check your information."),
            "error",
        )
        return render_template(
            "oidc/admin/client_add.html", form=form, menuitem="admin"
        )

    client_id = gen_salt(24)
    client_id_issued_at = datetime.datetime.now()
    client = Client(
        client_id=client_id,
        issue_date=client_id_issued_at,
        name=form["name"].data,
        contact=form["contact"].data,
        uri=form["uri"].data,
        grant_type=form["grant_type"].data,
        redirect_uris=[form["redirect_uris"].data],
        response_type=form["response_type"].data,
        scope=form["scope"].data.split(" "),
        token_endpoint_auth_method=form["token_endpoint_auth_method"].data,
        logo_uri=form["logo_uri"].data,
        tos_uri=form["tos_uri"].data,
        policy_uri=form["policy_uri"].data,
        software_id=form["software_id"].data,
        software_version=form["software_version"].data,
        jwk=form["jwk"].data,
        jwk_uri=form["jwk_uri"].data,
        preconsent=form["preconsent"].data,
        secret=""
        if form["token_endpoint_auth_method"].data == "none"
        else gen_salt(48),
    )
    client.audience = [client.dn]
    client.save()
    flash(
        _("The client has been created."),
        "success",
    )

    return redirect(url_for("oidc.clients.edit", client_id=client_id))
Example #40
0
def login(provider):
    if provider == "dgfr":
        remote_app = dgfr
    elif provider == "france-connect":
        remote_app = fc
    elif provider == "osm":
        remote_app = osm
    else:
        abort(400, 'Unkown login provider')
    return remote_app.authorize(
        callback=url_for('authorized', provider=provider, _external=True),
        state=security.gen_salt(10),
        nonce=security.gen_salt(10),
    )
Example #41
0
def token(slapd_connection, client, user):
    t = Token(
        access_token=gen_salt(48),
        audience=[client.dn],
        client=client.dn,
        subject=user.dn,
        token_type=None,
        refresh_token=gen_salt(48),
        scope="openid profile",
        issue_date=datetime.datetime.now(),
        lifetime=str(3600),
    )
    t.save(slapd_connection)
    return t
Example #42
0
def client():
    user = current_user()
    if not user:
        return redirect('/')
    item = Client(
        client_key=gen_salt(40),
        client_secret=gen_salt(50),
        _redirect_uris='http://127.0.0.1:8000/authorized',
        user_id=user.id,
    )
    db.session.add(item)
    db.session.commit()
    return jsonify(client_key=item.client_key,
                   client_secret=item.client_secret)
Example #43
0
def create_client():
    client = Client(
        client_id=gen_salt(40),
        client_secret=gen_salt(50),
        _redirect_uris='http://localhost:5000/authorized',
        _default_scopes='userinfo',
        _allowed_grant_types='authorization_code refresh_token password',
        user_id=None,
        is_confidential=True  # make a confidential client.
    )
    db.session.add(client)
    db.session.commit()
    print("client id: {0}\nclient secret: {1}".format(client.client_id,
                                                      client.client_secret))
Example #44
0
    def bootstrap_bumblebee():
        """
        Return or create a OAuthClient owned by the "bumblebee" user.
        Re-uses an existing client if "oauth_client" is encoded into the
        session cookie, otherwise writes a new client to the database.

        Similar logic performed for the OAuthToken.

        :return: OAuthToken instance
        """
        assert current_user.email == current_app.config['BOOTSTRAP_USER_EMAIL']

        salt_length = current_app.config.get('OAUTH2_CLIENT_ID_SALT_LEN', 40)
        scopes = ' '.join(current_app.config.get('BOOTSTRAP_SCOPES', []))
        expires = current_app.config.get('BOOTSTRAP_TOKEN_EXPIRES', 3600 * 24)
        client_name = current_app.config.get('BOOTSTRAP_CLIENT_NAME',
                                             'BB client')
        uid = current_user.get_id()

        client = OAuthClient(
            user_id=uid,
            name=client_name,
            description=client_name,
            is_confidential=False,
            is_internal=True,
            _default_scopes=scopes,
        )
        client.gen_salt()

        db.session.add(client)

        if isinstance(expires, int):
            expires = datetime.datetime.utcnow() + datetime.timedelta(
                seconds=expires)

        token = OAuthToken(
            client_id=client.client_id,
            user_id=uid,
            expires=expires,
            _scopes=scopes,
            access_token=gen_salt(salt_length),
            refresh_token=gen_salt(salt_length),
            is_personal=False,
            is_internal=True,
        )

        db.session.add(token)
        db.session.commit()
        return client, token
Example #45
0
    def put(self):
        """
        Generates a new API key
        :return: dict containing the API key data structure
        """

        client = OAuthClient.query.filter_by(
            user_id=current_user.get_id(),
            name=u'ADS API client',
        ).first()

        if client is None:  # If no client exists, create a new one
            client = OAuthClient(
                user_id=current_user.get_id(),
                name=u'ADS API client',
                description=u'ADS API client',
                is_confidential=False,
                is_internal=True,
                _default_scopes=' '.join(
                    current_app.config['USER_API_DEFAULT_SCOPES']
                ),
                ratelimit=1.0
            )
            client.gen_salt()

            token = OAuthToken(
                client_id=client.client_id,
                user_id=current_user.get_id(),
                access_token=gen_salt(40),
                refresh_token=gen_salt(40),
                expires=datetime.datetime(2500, 1, 1),
                _scopes=' '.join(
                    current_app.config['USER_API_DEFAULT_SCOPES']
                ),
                is_personal=False,
            )

            db.session.add(client)
            db.session.add(token)
            try:
                db.session.commit()
            except Exception, e:
                current_app.logger.error("Unknown DB error: {0}".format(e))
                abort(503)
            current_app.logger.info(
                "Created ADS API client+token for {0}".format(
                    current_user.email
                )
            )
Example #46
0
def create_test_token(user_id, client_id):
    """
    This function creates a access token for given test user.
    :param int | long user_id: user primary id
    :param string client_id: client unique id
    :rtype: Token
    """

    token = Token(client_id=client_id,
                  user_id=user_id,
                  token_type='Bearer',
                  access_token=gen_salt(60),
                  refresh_token=gen_salt(60),
                  expires=datetime(2020, 12, 31))
    return Token.save(token)
Example #47
0
    def create_user_token(client, expires=datetime.datetime(2500, 1, 1)):
        salt_length = current_app.config.get('OAUTH2_CLIENT_ID_SALT_LEN', 40)

        token = OAuthToken(
            client_id=client.client_id,
            user_id=client.user_id,
            access_token=gen_salt(salt_length),
            refresh_token=gen_salt(salt_length),
            expires=expires,
            _scopes=client._default_scopes,
            is_personal=False,
            is_internal=True,
        )

        return token
Example #48
0
def talent_pipeline(user_first, talent_pool):
    """
    Fixture adds talent pipeline
    """
    talent_pipeline = TalentPipeline(
        name=gen_salt(6),
        description=gen_salt(15),
        positions=2,
        date_needed=datetime.utcnow().isoformat(sep=' '),
        user_id=user_first.id,
        talent_pool_id=talent_pool.id)
    db.session.add(talent_pipeline)
    db.session.commit()

    return talent_pipeline
def client():
    user = current_user()
    if not user:
        return redirect('/')
    item = Client(
        client_key=gen_salt(40),
        client_secret=gen_salt(55),
        user_id=user.id,
    )
    db.session.add(item)
    db.session.commit()
    return jsonify(
        client_key=item.client_key,
        client_secret=item.client_secret,
    )
Example #50
0
    def put(self):
        """
        Generates a new API key
        :return: dict containing the API key data structure
        """

        client = OAuthClient.query.filter_by(
            user_id=current_user.get_id(),
            name=u'ADS API client',
        ).first()

        if client is None:  # If no client exists, create a new one
            client = OAuthClient(
                user_id=current_user.get_id(),
                name=u'ADS API client',
                description=u'ADS API client',
                is_confidential=False,
                is_internal=True,
                _default_scopes=' '.join(
                    current_app.config['USER_API_DEFAULT_SCOPES']
                ),
            )
            client.gen_salt()

            token = OAuthToken(
                client_id=client.client_id,
                user_id=current_user.get_id(),
                access_token=gen_salt(40),
                refresh_token=gen_salt(40),
                expires=datetime.datetime(2500, 1, 1),
                _scopes=' '.join(
                    current_app.config['USER_API_DEFAULT_SCOPES']
                ),
                is_personal=False,
            )

            db.session.add(client)
            db.session.add(token)
            try:
                db.session.commit()
            except Exception, e:
                current_app.logger.error("Unknown DB error: {0}".format(e))
                abort(503)
            current_app.logger.info(
                "Created ADS API client+token for {0}".format(
                    current_user.email
                )
            )
Example #51
0
    def bootstrap_bumblebee():
        """
        Return or create a OAuthClient owned by the "bumblebee" user.
        Re-uses an existing client if "oauth_client" is encoded into the
        session cookie, otherwise writes a new client to the database.

        Similar logic performed for the OAuthToken.

        :return: OAuthToken instance
        """
        assert current_user.email == current_app.config['BOOTSTRAP_USER_EMAIL']

        salt_length = current_app.config.get('OAUTH2_CLIENT_ID_SALT_LEN', 40)
        scopes = ' '.join(current_app.config.get('BOOTSTRAP_SCOPES', []))
        expires = current_app.config.get('BOOTSTRAP_TOKEN_EXPIRES', 3600*24)
        client_name = current_app.config.get('BOOTSTRAP_CLIENT_NAME', 'BB client')
        uid = current_user.get_id()

        client = OAuthClient(
            user_id=uid,
            name=client_name,
            description=client_name,
            is_confidential=False,
            is_internal=True,
            _default_scopes=scopes,
        )
        client.gen_salt()

        db.session.add(client)

        if isinstance(expires, int):
            expires = datetime.datetime.utcnow() + datetime.timedelta(
                seconds=expires)

        token = OAuthToken(
            client_id=client.client_id,
            user_id=uid,
            expires=expires,
            _scopes=scopes,
            access_token=gen_salt(salt_length),
            refresh_token=gen_salt(salt_length),
            is_personal=False,
            is_internal=True,
        )

        db.session.add(token)
        db.session.commit()
        return client, token
Example #52
0
def find_password(mobile,password,code):
    try:
        manage.cur.reconnect()
        manage.cur.reconnect()
        check=check_mobile(mobile)
        if check==0:
            real_code=manage.red.get("mobile_"+str(mobile))
            if str(real_code)==str(code):
                sql='select * from tab_user where status!=2 and mobile=%s limit 1'
                data=manage.cur.get(sql,mobile)
                if data:
                    word = str(password)
                    salt = gen_salt(6)
                    word = word + str(salt)
                    password_md5 = hashlib.md5(word).hexdigest()
                    sql='update tab_user set password=%s,salt=%s where id=%s'
                    manage.cur.execute(sql,password_md5,salt,data['id'])
                    return Message.json_mess(0, '找回成功', '')
                else:
                    return Message.json_mess(8, '用户不存在', '')
            else:
                return Message.json_mess(8, '验证码错误', '')
        else:
            return Message.json_mess(8, '找回失败', '')
    except Exception as e:
        current_app.logger.error(str(e))
        return Message.json_mess(8, '编辑失败', '')
    finally:
        manage.cur.close()
Example #53
0
def generate_invitation_codes():
    """生成注册码"""
    for i in xrange(0, 10):
        code = InvitationCode(code=gen_salt(16))
        db.session.add(code)
    db.session.commit()
    return redirect(request.referrer)
Example #54
0
    def __init__(self, app, evalex=False, request_key='werkzeug.request',
                 console_path='/console', console_init_func=None,
                 show_hidden_frames=False, lodgeit_url=None,
                 pin_security=True, pin_logging=True):
        if lodgeit_url is not None:
            from warnings import warn
            warn(DeprecationWarning('Werkzeug now pastes into gists.'))
        if not console_init_func:
            console_init_func = None
        self.app = app
        self.evalex = evalex
        self.frames = {}
        self.tracebacks = {}
        self.request_key = request_key
        self.console_path = console_path
        self.console_init_func = console_init_func
        self.show_hidden_frames = show_hidden_frames
        self.secret = gen_salt(20)
        self._failed_pin_auth = 0

        self.pin_logging = pin_logging
        if pin_security:
            # Print out the pin for the debugger on standard out.
            if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' and \
               pin_logging:
                _log('warning', ' * Debugger is active!')
                if self.pin is None:
                    _log('warning', ' * Debugger pin disabled.  '
                         'DEBUGGER UNSECURED!')
                else:
                    _log('info', ' * Debugger pin code: %s' % self.pin)
        else:
            self.pin = None
Example #55
0
def create_client():
    user = current_user()
    if not user:
        return redirect('/')
    if request.method == 'GET':
        return render_template('create_client.html')
    client = OAuth2Client(**request.form.to_dict(flat=True))
    client.user_id = user.id
    client.client_id = gen_salt(24)
    if client.token_endpoint_auth_method == 'none':
        client.client_secret = ''
    else:
        client.client_secret = gen_salt(48)
    db.session.add(client)
    db.session.commit()
    return redirect('/')
Example #56
0
    def create_personal(cls, name, user_id, scopes=None, is_internal=False):
        """
        Create a personal access token (a token that is bound to a specific
        user and which doesn't expire).
        """
        scopes = " ".join(scopes) if scopes else ""

        c = OAuthClient(name=name,
                        user_id=user_id,
                        is_internal=True,
                        is_confidential=False,
                        _default_scopes=scopes)
        c.gen_salt()

        t = OAuthToken(
            client_id=c.client_id,
            user_id=user_id,
            access_token=gen_salt(
                current_app.config.get('OAUTH2_TOKEN_PERSONAL_SALT_LEN', 40)),
            expires=None,
            _scopes=scopes,
            is_personal=True,
            is_internal=is_internal,
        )

        db.session.add(c)
        db.session.add(t)
        db.session.commit()

        return t
Example #57
0
def login():
    request_data = request.form
    user_name = request_data["user_name"]
    password = request_data["password"]
    result, info = user_m.check(user_name, password)
    if result is False:
        return info
    if info["tel"] is None:
        session["user_name"] = info["account"]
        session["bind_token"] = gen_salt(57)
        session["expires_in"] = datetime.now() + timedelta(seconds=300)
        session["password"] = password
        return redirect("%s/tel/" % url_prefix)
    if "remember" in request_data and request_data["remember"] == "on":
        remember = True
    else:
        remember = False
    user = User()
    user.user_name = info["account"]
    login_user(user, remember=remember)
    session["role"] = info["role"]
    if "next" in request_data and request_data["next"] != "":
        return redirect(request_data["next"])
    if session["role"] == 0:
            return u"您还没有任何权限,请联系管理员授权"
    else:
        resp = redirect(url_prefix + "/portal/")
        return resp
Example #58
0
    def test_cookie_forwarding(self):
        """
        Test that cookies get properly passed by the SolrInterface
        """
        def request_callback(request, uri, headers):
            return 200, headers, request.headers.get('cookie')

        httpretty.register_uri(
            httpretty.POST,
            self.app.config.get('SOLR_SERVICE_SEARCH_HANDLER'),
            body=request_callback,
        )
        with self.client as c:
            cookie_value = gen_salt(200)

            # This cookie should be forwarded
            c.set_cookie(
                'localhost',
                self.app.config.get("SOLR_SERVICE_FORWARD_COOKIE_NAME"),
                cookie_value)

            # This cookie should not be forwarded
            c.set_cookie('localhost', 'cookie_name', 'cookie_value')

            r = c.get(url_for('search'), query_string={'q': 'star'})

            # One and only one cookie
            self.assertEqual(len(r.data.split('=')), 2)

            # This forwarded cookie should match the one we gave originally
            rcookie_value = r.data.split('=')[1]
            self.assertEqual(rcookie_value, cookie_value)
Example #59
0
    def save(self, user):
        client_id = gen_salt(48)
        client_secret = gen_salt(78)

        client = Client(client_id=client_id,
                        client_secret=client_secret,
                        client_name=self.client_name.data,
                        client_uri=self.client_uri.data,
                        redirect_uri=self.redirect_uri.data,
                        grant_type=self.grant_type.data,
                        response_type=self.response_type.data,
                        scope=self.scope.data,
                        user_id=user.id)
        db.session.add(client)
        db.session.commit()
        return client
Example #60
0
    def create_personal(cls, name, user_id, scopes=None, is_internal=False):
        """Create a personal access token.

        A token that is bound to a specific user and which doesn't expire, i.e.
        similar to the concept of an API key.
        """
        scopes = " ".join(scopes) if scopes else ""

        c = Client(name=name, user_id=user_id, is_internal=True, is_confidential=False, _default_scopes=scopes)
        c.gen_salt()

        t = Token(
            client_id=c.client_id,
            user_id=user_id,
            access_token=gen_salt(current_app.config.get("OAUTH2_TOKEN_PERSONAL_SALT_LEN")),
            expires=None,
            _scopes=scopes,
            is_personal=True,
            is_internal=is_internal,
        )

        db.session.add(c)
        db.session.add(t)
        db.session.commit()

        return t