Example #1
0
File: user.py Project: mariajbp/LI4
    def post(self):
        body = request.json
        if not body:
            return {"error": "No json body found on request"}

        id_user = body['id_user']
        email = body['email']
        password = body['password']
        name = body['name']

        ################## Input Validation ##################
        from common.utils import params_validation, VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX, VALID_EMAIL_REGEX

        params = [id_user, name, password, email]
        rgxs = [
            VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX,
            VALID_EMAIL_REGEX
        ]

        try:
            params_validation(rgxs, params)
        except ErrorCodeException as ec:
            return error_code(ec), 400
        ######################################################

        try:
            User.add_user(
                User(body['id_user'], body['email'], body['password'],
                     body['name'], int(body['permissions'])))
            return success()
        except ErrorCodeException as ec:
            return error_code(ec)
Example #2
0
File: user.py Project: mariajbp/LI4
    def get(self):
        sender_user = User.get_user(get_jwt_identity())

        # If id_user hasn't been specified check permissions for listing all users
        if not sender_user.check_permission(Permissions.ADMIN):
            return forbidden(), 401
        return {"users": [u.to_json() for u in User.get_all()]}
Example #3
0
File: user.py Project: mariajbp/LI4
    def put(self):
        sender_id_user = get_jwt_identity()
        args = UserAPI.parser_put.parse_args()

        target_id_user = args['id_user']
        old_password = args['old_password']
        new_password = args['new_password']

        if old_password != None and new_password != None:
            try:
                u = User.get_user(target_id_user)
                tmp = User.get_user(sender_id_user)
                if sender_id_user != target_id_user and not tmp.check_permission(
                        Permissions.ADMIN):
                    return forbidden(), 403
                else:
                    if u.check_password(old_password):
                        u.set_password(new_password)
                        return success()
                    else:
                        return error_message("Incorrect old password!"), 500
            except ErrorCodeException as ec:
                return error_code(ec), 500
        else:
            return error_message("Argument required"), 401
Example #4
0
    def post(self):
        email = self.request.get("edEmail", "")
        name = self.request.get("edName", "")
        address = self.request.get("edAddress", "")
        phone = self.request.get("edPhone", "")
        operation = self.request.get("edOp", "")

        if email and operation:
            if operation == "add":
                user = User()
                user.email = email
                user.name = name
                user.address = address
                user.phone = phone
                user.put()
                time.sleep(1)
            elif operation == "delete":
                user = User.query(User.email == email)
                if user:
                    user = user.get()
                    user.key.delete()
                    time.sleep(1)
                else:
                    self.redirect("/error?msg=user was not found")
            self.redirect("/admin")
        else:
            self.redirect("/error?msg=email and operation needed")

        return
Example #5
0
File: auth.py Project: mariajbp/LI4
    def post(self):
        args = RegisterAPI.parser_post.parse_args()

        id_user = args['id_user']
        name = args['name']
        password = args['password']
        email = args['email']

        if not (id_user and name and password and email):
            return error_message("Insuficient arguments"), 400

        ################## Input Validation ##################
        from common.utils import params_validation, VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX, VALID_EMAIL_REGEX

        params = [id_user, name, password, email]
        rgxs = [
            VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX,
            VALID_EMAIL_REGEX
        ]

        try:
            params_validation(rgxs, params)
        except ErrorCodeException as ec:
            return error_code(ec), 400
        ######################################################

        try:
            User.add_user(
                User(id_user, email, password, name, Permissions.USER))
            return success(), 200
        except ErrorCodeException as ec:
            return error_code(ec), 400
Example #6
0
    def get(self):
        try:
            session_id = self.request.GET['session_id']
        except:
            self.redirect("/error?msg=missing session id")
            return

        try:
            client_id = self.request.GET['client_id']
        except:
            self.redirect("/error?msg=missing client id")
            return

        user = users.get_current_user()

        if user:
            if User.chk_allowed(user.email()):
                try:
                    session = ndb.Key(urlsafe=session_id).get()
                except:
                    self.redirect(
                        "/error?msg=key does not exist for session creating report"
                    )
                    return

                try:
                    user_info = User.query(User.email == user.email()).get()
                except:
                    self.redirect("/error?msg=user info was not found")
                    return

                try:
                    client = ndb.Key(urlsafe=client_id).get()
                except:
                    self.redirect(
                        "/error?msg=key does not exist for client creating report for session"
                    )
                    return

                template_values = {
                    "user_info": user_info,
                    "info": AppInfo,
                    "client": client,
                    "session": session,
                }

                jinja = jinja2.get_jinja2(app=self.app)
                self.response.write(
                    jinja.render_template("reportSession.html",
                                          **template_values))
            else:
                self.redirect("/nouser")
        else:
            self.redirect("/")
Example #7
0
File: user.py Project: mariajbp/LI4
    def get(self, id_user):
        sender_user = User.get_user(get_jwt_identity())

        # Check permissions for listing other users rather than himself
        if (not sender_user.check_permission(
                Permissions.ADMIN)) and (not id_user == sender_user.id_user):
            return forbidden(), 403

        try:
            return {"user": User.get_user(id_user).to_json()}
        except ErrorCodeException as ec:
            return error_code(ec)
Example #8
0
File: user.py Project: mariajbp/LI4
    def delete(self):
        args = UserAPI.parser_del.parse_args()
        id_user = args['id_user']

        if not id_user:
            return {"error": "Argument required"}

        try:
            User.delete(id_user)
            return success()
        except ErrorCodeException as ec:
            return error_code(ec)
Example #9
0
    def get(self, id_user):
        args = UserTicketAPI.parser.parse_args()

        target_id_ticket = args['id_ticket']

        sender_user = User.get_user(get_jwt_identity())

        if sender_user.id_user != id_user and not sender_user.check_permission(
                Permissions.ADMIN):
            return {'error': 'Unauthorized!'}, 401

        # Checks if id_ticket has been specified
        if target_id_ticket != None:
            try:
                t = Ticket.get_ticket(target_id_ticket)
                if t.id_user == id_user:
                    return {
                        "ticket":
                        Ticket.get_ticket(target_id_ticket).to_json()
                    }
            except ErrorCodeException as ec:
                return error_code(ec)

        else:
            return {
                "owned_tickets":
                [t.to_json() for t in Ticket.get_not_used(id_user=id_user)]
            }
Example #10
0
 def _to_python(self, value, state):
     from model.users import User
     q = User.all()
     q.filter('userid =', value)
     if list(q.fetch(100)):
         m = 'User ID %s already exists' % value
         raise formencode.Invalid(m, value, state)
     return value
Example #11
0
    def add_user():
        data.validate(
            required_fields=['id', 'user_name', 'user_email', 'user_phone'],
            error_message='Form has errors')

        org = Organization.get_by_id(data.id)
        if not org:
            return error('Organization not found')

        user = get_user_by_email(data.user_email)
        if not user:
            user = User(raw_name=data.user_name,
                        email=data.user_email,
                        phone=data.user_phone,
                        account_verified=True)
            user.org = [org.key]
        else:
            user.org = list(set(user.org + [org.key]))

        new_password = generate_random_password()
        user.password = web_auth.signed_password(new_password)
        user.put()

        TrackrRoles.get_or_insert('roles',
                                  parent=user.key,
                                  kind=['Admin', 'Staff'])

        mail_body = render('/emails/welcome.mako',
                           new_password=new_password,
                           user=user)
        send_email(data.user_email, mail_body, 'Welcome to Trackr')

        return 'Account Created'
Example #12
0
    def get(self):
        users = User.query()

        template_values = {
            "users": users,
            "info": AppInfo,
        }

        jinja = jinja2.get_jinja2(app=self.app)
        self.response.write(jinja.render_template("admin.html", **template_values))
Example #13
0
    def new():
        data.validate(pricing=Required(float),
                      min_pricing=Required(float),
                      required_fields=[
                          'name', 'id', 'short_code', 'brand_name',
                          'support_number', 'admin_name', 'admin_email',
                          'admin_phone'
                      ],
                      error_message='Form has errors')

        org = Organization.get_by_id(data.id)
        if not org:
            org = Organization(id=data.id,
                               name=data.name,
                               secure_signup_step='Approved')
            set_api_creds(org)
            org.put()

        user = get_user_by_email(data.admin_email)
        if not user:
            user = User(raw_name=data.admin_name,
                        email=data.admin_email,
                        phone=data.admin_phone,
                        account_verified=True)
            user.org = [org.key]
        else:
            user.org = list(set(user.org + [org.key]))

        new_password = generate_random_password()
        user.password = web_auth.signed_password(new_password)
        user.put()

        org.admin = user.key
        org.put()

        if not Trackr.get_by_id(org.key.id()):
            Trackr(id=org.key.id(),
                   org=org.key,
                   users=[user.key],
                   short_code=data.short_code,
                   brand_name=data.brand_name,
                   support_number=data.support_number,
                   secure_pricing=data.pricing,
                   secure_min_pricing=data.min_pricing).put()

        TrackrRoles.get_or_insert('roles',
                                  parent=user.key,
                                  kind=['Admin', 'Staff'])

        mail_body = render('/emails/welcome.mako',
                           new_password=new_password,
                           user=user)
        send_email(data.admin_email, mail_body, 'Welcome to Trackr')

        return 'Account Created'
Example #14
0
 def create(self, db: Session, obj_in: dict) -> User:
     db_obj = User(
         username=obj_in.get('username'),
         password=bytes(get_password_hash(obj_in.get('password')),
                        encoding='utf-8'),
         remark=obj_in.get('remark'),
         state=obj_in.get('state'),
         is_superuser=obj_in.get('is_superuser'),
     )
     db.add(db_obj)
     db.commit()
     db.refresh(db_obj)
     return db_obj
Example #15
0
    def init_controller(controller, payload):
        if payload:
            try:
                user_id = int(payload['user'])
            except ValueError:
                user_id = payload['user']

            user = User.get_by_id(user_id)
            DefaultWebAuth.init_controller(controller, user)
            controller.set_env(realm=payload['realm'])
        else:
            controller.set_env(user=None)
            controller.user_acl = []
Example #16
0
def payment(productid, livraison):
    produit = Products.getProduit(productid)
    produitAct = Product(produit)
    cout = produitAct.getCost()

    form = UserForm()
    if form.validate_on_submit():
        print(form)
        first_name = form.first_name.data
        last_name = form.last_name.data
        birthday = form.birthday.data
        nationality = form.nationality.data
        country_of_residence = form.country_of_residence.data
        email = form.email.data
        cardNumber = form.cardNumber.data
        cardCvx = form.cardCvx.data
        cardExpirationDate = form.cardExpirationDate.data

        acheteur = User(first_name, last_name, birthday, nationality, country_of_residence, email, cardNumber, cardCvx, cardExpirationDate)
        res = acheteur.pay(cout, livraison)

        return render_template('payment.html', produit = produit, form = form, livraison = livraison, cout = cout, res = res)

    return render_template('payment.html', produit = produit, livraison = livraison, cout = cout, form = form)
Example #17
0
def set_as_used(id_ticket, id_user):

    t = Ticket.get_ticket(id_ticket)
    if t == None:
        raise ErrorCodeException(ErrorCode.TICKET_DOESNT_EXISTS)

    if t.id_user != id_user:
        raise ErrorCodeException(ErrorCode.TICKET_DOESNT_BELONG_TO_USER)

    if User.get_user(id_user) == None:
        raise ErrorCodeException(ErrorCode.USER_DOESNT_EXISTS)

    if t.used == True:
        raise ErrorCodeException(ErrorCode.TICKET_ALREADY_USED)
    t.set_used()

    History.add_entry(History(id_ticket=unhexlify(id_ticket), id_user=id_user))
Example #18
0
File: auth.py Project: mariajbp/LI4
    def post(self):
        auth = request.authorization

        #generate_password_hash("epah_mas_que_chatice")

        if not auth or not auth.username or not auth.password:
            return make_response(
                unauthorized("Fields not specified"), 401,
                {'WWW-Authenticate': 'Basic realm="Login required!"'})

        try:
            user = User.get_user(auth.username)
        except ErrorCodeException as ec:
            return error_code(ec), 401, {
                'WWW-Authenticate': 'Basic realm="Login required!"'
            }

        #if not user:
        #    return make_response(error_code(ErrorCode.USER_DOESNT_EXISTS) , 401 , {'WWW-Authenticate' : 'Basic realm="Login required!"'})

        if user.check_password(auth.password):
            token = create_access_token(
                identity=str(user.id_user),
                user_claims={"permissions": user.permissions},
                expires_delta=datetime.timedelta(weeks=20))

            decoded_token = decode_token(token)
            added = SessionTable.add(
                user.id_user, decoded_token['jti'],
                datetime.datetime.fromtimestamp(decoded_token['exp'])
            )  # Old code #token = jwt.encode({'id_user' : auth.username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=5)}, app.config['TOKEN_GEN_KEY'])
            #print("Sessions:",SessionTable.size(user.id_user))

            if added:
                return make_response(jsonify({'token': token}), 200)
            else:
                return make_response(
                    unauthorized("Unable to login"), 401,
                    {'WWW-Authenticate': 'Basic realm="Login required!"'})

        return make_response(
            error_code(ErrorCode.WRONG_PASSWORD), 401,
            {'WWW-Authenticate': 'Basic realm="Login required!"'})
Example #19
0
    def get(self):
        user = users.get_current_user()

        try:
            client_id = self.request.GET['client_id']
        except:
            self.redirect(
                "/error?msg=missing client_id for sessions management")
            return

        if user:
            if User.chk_allowed(user.email()):
                user_name = user.nickname()
                access_link = users.create_logout_url("/")

                try:
                    client = ndb.Key(urlsafe=client_id).get()
                except:
                    self.redirect(
                        "/error?msg=client key was not found for sessions management"
                    )
                    return

                sessions = Session.query(
                    Session.dni == client.dni).order(-Session.added)

                template_values = {
                    "user_name": user_name,
                    "access_link": access_link,
                    "client": client,
                    "sessions": sessions,
                    "info": AppInfo,
                }

                jinja = jinja2.get_jinja2(app=self.app)
                self.response.write(
                    jinja.render_template("sessionsManagement.html",
                                          **template_values))
            else:
                self.redirect("/nouser")
        else:
            self.redirect("/")
Example #20
0
    def get(self):
        user = users.get_current_user()

        if user:
            if User.chk_allowed(user.email()):
                user_name = user.nickname()
                access_link = users.create_logout_url("/")
                clients = Client.query().order(Client.surname)

                template_values = {
                    "info": AppInfo,
                    "user_name": user_name,
                    "access_link": access_link,
                    "clients": clients,
                }

                jinja = jinja2.get_jinja2(app=self.app)
                self.response.write(
                    jinja.render_template("clientsManagement.html",
                                          **template_values))
            else:
                self.redirect("/nouser")
        else:
            self.redirect("/")
Example #21
0
File: app.py Project: mariajbp/LI4
def populate():
    from binascii import unhexlify
    # Insert some users
    try:
        User.add_user(User("a12345","*****@*****.**","epah_mas_que_chatice","António Barosa",permissions=5))
    except:
        pass
    try:
        User.add_user(User("a11111","*****@*****.**","epah_mas_que_chatice","Adelino Costa"))
    except:
        pass
    try:
        User.add_user(User("a22222","*****@*****.**","epah_mas_que_chatice","Rosa Matilde"))
    except:
        pass
    try:
        User.add_user(User("a33333","*****@*****.**","epah_mas_que_chatice","Fernando Magalhães"))
    except:
        pass 
        
    # Insert some ticket types
    try:
        TicketType.add_type(TicketType(1,1.8,"simple"))
    except:
        pass
    try:
        TicketType.add_type(TicketType(2,2.5,"complete"))
    except:
        pass

    
    from model.meal import MealType , Location , Meal
    try:
        MealType.add_meal_type(MealType("lunch"))
    except:
        pass
    try:
        MealType.add_meal_type(MealType("dinner"))
    except:
        pass
    try:
        MealType.add_meal_type(MealType("lunch_veg"))
    except:
        pass
    try:
        MealType.add_meal_type(MealType("dinner_veg"))
    except:
        pass

    try:
        Location.add_location(Location("azurem"))
    except:
        pass
    try:
        Location.add_location(Location("gualtar"))
    except:
        pass

    from datetime import date
    try:
        Meal.add_meal(Meal(date.fromisoformat('2019-12-04'),1,1,soup="Sopa de Frango",main_dish="Frango"))
    except:
        pass
Example #22
0
async def isUser(item: users.User):
    data = item.dict()
    resp = get_user_json_data(data)
    return {"Result": resp}
Example #23
0
def test_empty_signup(app):
    app.user.sign_up(User(firstname="", email="", password=""))
Example #24
0
def log_user(from_number):
    if from_number in users:
        name = users[from_number]
    else:
        name = f"Friend_{from_number}"
        users[from_number] = User(name, from_number)
Example #25
0
def test_signup(app):
    app.user.sign_up(
        User(firstname="Firstname123",
             email="*****@*****.**",
             password="******"))