Beispiel #1
0
    def createuser():
        """Create an user"""
        username = click.prompt("Username", type=str)
        email = click.prompt("Email", type=str)
        password = click.prompt("Password",
                                type=str,
                                hide_input=True,
                                confirmation_prompt=True)
        while True:
            role = click.prompt("Role [admin/user]", type=str)
            if role == "admin" or role == "user":
                break

        if click.confirm("Do you want to continue ?"):
            role = Role.query.filter(Role.name == role).first()
            if not role:
                raise click.UsageError("Roles not present in database")
            u = user_datastore.create_user(name=username,
                                           email=email,
                                           password=encrypt_password(password),
                                           roles=[role])

            actor = create_actor(u)
            actor.user = u
            actor.user_id = u.id
            db.session.add(actor)

            db.session.commit()

            if FSConfirmable.requires_confirmation(u):
                FSConfirmable.send_confirmation_instructions(u)
                print("Look at your emails for validation instructions.")
Beispiel #2
0
    def create_actor_for_registered_user(app, user, confirm_token):
        if not user:

            return
        actor = create_actor(user)
        actor.user = user
        actor.user_id = user.id
        db.session.add(actor)
        db.session.commit()
Beispiel #3
0
    def __init__(self, args):
        self.actor = models.create_actor(args.feature, 18).cuda()
        self.critic = models.create_critic(args.feature).cuda()
        self.old_actor = models.create_actor(args.feature, 18).cuda()
        self.actor_optimizer = optim.Adam(self.actor.parameters(),
                                          lr=args.actorlr)
        self.critic_optimizer = optim.Adam(self.critic.parameters(),
                                           lr=args.criticlr)
        self.batch_size = args.batch_size

        self.epoch = 0
        self.plot_epoch = []
        self.plot_reward = []
        self.best = -1000
        import threading as th
        self.lock = th.Lock()
        self.msize = 0
        self.GAMMA = args.gamma
        self.S_DIM = args.feature
        self.A_DIM = 18
Beispiel #4
0
def accounts():
    """
    Register an account
    The method is available to apps with a token obtained via the client credentials grant.
    It creates a user and account records, as well as an access token for the app that initiated the request.
    The method returns the access token, which the app should save for later.
    ---
    tags:
        - Accounts
    definitions:
      Token:
        type: object
        properties:
            access_token:
                type: string
            token_type:
                type: string
            scope:
                type: string
            created_at:
                type: integer
    responses:
      200:
        description: Returns Token
        schema:
            $ref: '#/definitions/Token'
    """

    if not current_app.config["REGISTRATION_ENABLED"]:
        abort(403)

    errors = {}

    # Get the bearer token
    bearer = None
    if "Authorization" in request.headers:
        b = request.headers.get("Authorization")
        b = b.strip().split(" ")
        if len(b) == 2:
            bearer = b[1]
        else:
            errors["bearer"] = ["API Bearer Authorization format issue"]
    else:
        current_app.logger.info(
            "/api/v1/accounts: no Authorization bearer given")

    if not request.json:
        abort(400)

    if "nickname" not in request.json:
        errors["nickname"] = ["nickname is missing"]
    if "email" not in request.json:
        errors["email"] = ["email is missing"]
    if "fullname" not in request.json:
        errors["fullname"] = ["fullname is missing"]
    if "password" not in request.json:
        errors["password"] = ["password is missing"]
    if "confirm" not in request.json:
        errors["confirm"] = ["password confirm is missing"]
    if "agreement" not in request.json:
        errors["agreement"] = ["agreement is missing"]

    if len(errors) > 0:
        return jsonify({"error": str(errors)}), 400

    if forbidden_username(request.json["nickname"]):
        return jsonify(
            {"error": str({"nickname":
                           ["this username cannot be used"]})}), 400

    if request.json["password"] != request.json["confirm"]:
        return jsonify(
            {"error": str({"confirm": ["passwords doesn't match"]})}), 400

    if "agreement" not in request.json:
        return jsonify({
            "error":
            str({"agreement": ["you need to accept the terms and conditions"]})
        }), 400

    # Check if user already exists by local user username
    user = User.query.filter(User.name == request.json["username"]).first()
    if user:
        return jsonify({"error": str({"ap_id":
                                      ["has already been taken"]})}), 400

    # Check if user already exists by old local user (Actors)
    user = Actor.query.filter(
        Actor.preferred_username == request.json["username"]).first()
    if user:
        return jsonify({"error": str({"ap_id":
                                      ["has already been taken"]})}), 400

    # Check if user already exists by email
    user = User.query.filter(User.email == request.json["email"]).first()
    if user:
        return jsonify({"error": str({"email":
                                      ["has already been taken"]})}), 400

    # Check username is valid
    # /^[a-zA-Z\d]+$/
    if not username_is_legal.match(request.json["username"]):
        return jsonify({
            "error":
            str({"ap_id": ["should contains only letters and numbers"]})
        }), 400

    # Proceed to register the user
    role = Role.query.filter(Role.name == "user").first()
    if not role:
        return jsonify({"error": "server error"}), 500

    u = user_datastore.create_user(
        name=request.json["username"],
        email=request.json["email"],
        display_name=request.json["fullname"],
        password=hash_password(request.json["password"]),
        roles=[role],
    )

    actor = create_actor(u)
    actor.user = u
    actor.user_id = u.id
    if "bio" in request.json:
        actor.summary = request.json["bio"]

    db.session.add(actor)
    db.session.commit()

    if FSConfirmable.requires_confirmation(u):
        FSConfirmable.send_confirmation_instructions(u)

    # get the matching item from the given bearer
    bearer_item = OAuth2Token.query.filter(
        OAuth2Token.access_token == bearer).first()
    if not bearer_item:
        abort(400)
    client_item = OAuth2Client.query.filter(
        OAuth2Client.client_id == bearer_item.client_id).first()
    if not client_item:
        abort(400)

    # https://github.com/lepture/authlib/blob/master/authlib/oauth2/rfc6749/grants/base.py#L51
    token = authorization.generate_token(client_item.client_id,
                                         "client_credentials",
                                         user=u,
                                         scope=client_item.scope,
                                         expires_in=None)

    tok = OAuth2Token()
    tok.user_id = u.id
    tok.client_id = client_item.client_id
    # the frontend should request an app every time it doesn't have one in local storage
    # and this app should allow delivering a somewhat non usuable Token
    # token which gets sent to this endpoint and gets used to get back the right client_id
    # to associate in the database...
    tok.token_type = token["token_type"]
    tok.access_token = token["access_token"]
    tok.refresh_token = None
    tok.scope = token["scope"]
    tok.revoked = False
    tok.expires_in = token["expires_in"]
    db.session.add(tok)
    db.session.commit()

    return jsonify({**token, "created_at": tok.issued_at}), 200
Beispiel #5
0
 def __init__(self,wid,diff):
      self.wid = wid
      self.env = RunEnv(visualize=False)
      self.dif = diff
      self.Actor = models.create_actor(args.feature,18)
Beispiel #6
0
 def __init__(self):
      self.Actor = models.create_actor(args.feature,18)
      self.Critic = models.create_critic(args.feature)
      self.Actor_optimizer = optim.Adam(self.Actor.parameters(), lr = 1e-4)
      self.Critic_optimizer = optim.Adam(self.Critic.parameters(), lr = 3e-4)