Пример #1
0
Файл: api.py Проект: mazz/kifu
def account_activate(request):
    """Reset a user after being suspended

    :param username: required to know what user we're resetting
    :param activation: code needed to activate
    :param password: new password to use for the user

    """
    params = request.params

    username = params.get('username', None)
    activation = params.get('code', None)
    password = params.get('password', None)
    new_username = params.get('new_username', None)

    if username is None and activation is None and password is None:
        # then try to get the same fields out of a json body
        json_body = request.json_body
        username = json_body.get('username', None)
        activation = json_body.get('code', None)
        password = json_body.get('password', None)
        new_username = json_body.get('new_username', None)

    if not UserMgr.acceptable_password(password):
        request.response.status_int = 406
        return _api_response(request, {
            'error': "Come on, pick a real password please",
        })

    res = ActivationMgr.activate_user(username, activation, password)

    if res:
        # success so respond nicely
        AuthLog.reactivate(username, success=True, code=activation)

        # if there's a new username and it's not the same as our current
        # username, update it
        if new_username and new_username != username:
            try:
                user = UserMgr.get(username=username)
                user.username = new_username
            except IntegrityError, exc:
                request.response.status_int = 500
                return _api_response(request, {
                    'error': 'There was an issue setting your new username',
                    'exc': str(exc)
                })

        return _api_response(request, {
            'message': "Account activated, please log in.",
            'username': username,
        })
Пример #2
0
def account_activate(request):
    """Reset a user after being suspended

    :param username: required to know what user we're resetting
    :param activation: code needed to activate
    :param password: new password to use for the user

    """
    params = request.params

    username = params.get('username', None)
    activation = params.get('code', None)
    password = params.get('password', None)
    new_username = params.get('new_username', None)

    if username is None and activation is None and password is None:
        # then try to get the same fields out of a json body
        json_body = request.json_body
        username = json_body.get('username', None)
        activation = json_body.get('code', None)
        password = json_body.get('password', None)
        new_username = json_body.get('new_username', None)

    if not UserMgr.acceptable_password(password):
        request.response.status_int = 406
        return _api_response(request, {
            'error': "Come on, pick a real password please",
        })

    res = ActivationMgr.activate_user(username, activation, password)

    if res:
        # success so respond nicely
        AuthLog.reactivate(username, success=True, code=activation)

        # if there's a new username and it's not the same as our current
        # username, update it
        if new_username and new_username != username:
            try:
                user = UserMgr.get(username=username)
                user.username = new_username
            except IntegrityError, exc:
                request.response.status_int = 500
                return _api_response(request, {
                    'error': 'There was an issue setting your new username',
                    'exc': str(exc)
                })

        return _api_response(request, {
            'message': "Account activated, please log in.",
            'username': username,
        })
Пример #3
0
Файл: api.py Проект: mazz/kifu
def del_user(request):
    """Remove a bad user from the system via the api.

    For admin use only.

    Removes all of a user's bookmarks before removing the user.

    """
    mdict = request.matchdict

    # Submit a username.
    del_username = mdict.get('username', None)

    if del_username is None:
        LOG.error('No username to remove.')
        request.response.status_int = 400
        return _api_response(request, {
            'error': 'Bad Request: No username to remove.',
        })

    u = UserMgr.get(username=del_username)

    if not u:
        LOG.error('Username not found.')
        request.response.status_int = 404
        return _api_response(request, {
            'error': 'User not found.',
        })
Пример #4
0
def suspend_acct(request):
    """Reset a user account to enable them to change their password"""
    params = request.params
    user = request.user

    # we need to get the user from the email
    email = params.get('email', None)

    if email is None and hasattr(request, 'json_body'):
        # try the json body
        email = request.json_body.get('email', None)

    if user is None and email is None:
        request.response.status_int = 406
        return _api_response(request, {
            'error': "Please submit an email address",
        })

    if user is None and email is not None:
        user = UserMgr.get(email=email)

    if user is None:
        request.response.status_int = 404
        return _api_response(request, {
            'error': "Please submit a valid address",
            'email': email
        })

    # check if we've already gotten an activation for this user
    if user.activation is not None:
        request.response.status_int = 406
        return _api_response(request, {
            'error': """You've already marked your account for reactivation. Please check your email for the reactivation link. Make sure to check your spam folder.""",
            'username': user.username,
        })

    # mark them for reactivation
    user.reactivate("FORGOTTEN")

    # log it
    AuthLog.reactivate(user.username)

    # and then send an email notification
    # @todo the email side of things
    settings = request.registry.settings
    msg = ReactivateMsg(user.email,
                        "Activate your account",
                        settings)

    msg.send({
        'url': request.route_url(
            'reset',
            username=user.username,
            reset_key=user.activation.code),
        'username': user.username
    })

    return _api_response(request, {
        'message': """Your account has been marked for reactivation. Please check your email for instructions to reset your password.""",
    })
Пример #5
0
Файл: api.py Проект: mazz/kifu
def accounts_invites(request):
    """Return a list of the accounts that aren't activated."""
    user_list = UserMgr.get_list()
    ret = {
        'users': [(u.username, u.invite_ct) for u in user_list],
    }
    return _api_response(request, ret)
Пример #6
0
def del_user(request):
    """Remove a bad user from the system via the api.

    For admin use only.

    Removes all of a user's bookmarks before removing the user.

    """
    mdict = request.matchdict

    # Submit a username.
    del_username = mdict.get('username', None)

    if del_username is None:
        LOG.error('No username to remove.')
        request.response.status_int = 400
        return _api_response(request, {
            'error': 'Bad Request: No username to remove.',
        })

    u = UserMgr.get(username=del_username)

    if not u:
        LOG.error('Username not found.')
        request.response.status_int = 404
        return _api_response(request, {
            'error': 'User not found.',
        })
Пример #7
0
Файл: api.py Проект: mazz/kifu
def suspend_acct(request):
    """Reset a user account to enable them to change their password"""
    params = request.params
    user = request.user

    # we need to get the user from the email
    email = params.get('email', None)

    if email is None and hasattr(request, 'json_body'):
        # try the json body
        email = request.json_body.get('email', None)

    if user is None and email is None:
        request.response.status_int = 406
        return _api_response(request, {
            'error': "Please submit an email address",
        })

    if user is None and email is not None:
        user = UserMgr.get(email=email)

    if user is None:
        request.response.status_int = 404
        return _api_response(request, {
            'error': "Please submit a valid address",
            'email': email
        })

    # check if we've already gotten an activation for this user
    if user.activation is not None:
        request.response.status_int = 406
        return _api_response(request, {
            'error': """You've already marked your account for reactivation. Please check your email for the reactivation link. Make sure to check your spam folder.""",
            'username': user.username,
        })

    # mark them for reactivation
    user.reactivate("FORGOTTEN")

    # log it
    AuthLog.reactivate(user.username)

    # and then send an email notification
    # @todo the email side of things
    settings = request.registry.settings
    msg = ReactivateMsg(user.email,
                        "Activate your account",
                        settings)

    msg.send({
        'url': request.route_url(
            'reset',
            username=user.username,
            reset_key=user.activation.code),
        'username': user.username
    })

    return _api_response(request, {
        'message': """Your account has been marked for reactivation. Please check your email for instructions to reset your password.""",
    })
Пример #8
0
def accounts_invites(request):
    """Return a list of the accounts that aren't activated."""
    user_list = UserMgr.get_list()
    ret = {
        'users': [(u.username, u.invite_ct) for u in user_list],
    }
    return _api_response(request, ret)
Пример #9
0
 def __init__(self, user_obj):
     self.user_obj = user_obj
     self.data_mgr = DataMgr.DataMgr("",
                                     AnalysisScheduler.AnalysisScheduler(),
                                     None, None)
     self.user_mgr = UserMgr.UserMgr(None)
     super(WorkoutPlanGenerator, self).__init__()
Пример #10
0
Файл: api.py Проект: mazz/kifu
def accounts_inactive(request):
    """Return a list of the accounts that aren't activated."""
    user_list = UserMgr.get_list(active=False)
    ret = {
        'count': len(user_list),
        'users': [dict(h) for h in user_list],
    }
    return _api_response(request, ret)
Пример #11
0
 def __init__(self, activity_type, activity_user_id, data_mgr):
     SensorAnalyzer.SensorAnalyzer.__init__(self, Keys.APP_POWER_KEY, Units.get_power_units_str(), activity_type)
     self.data_mgr = data_mgr
     self.user_mgr = UserMgr.UserMgr(None)
     self.np_buf = []
     self.current_30_sec_buf = []
     self.current_30_sec_buf_start_time = 0
     self.activity_user_id = activity_user_id
Пример #12
0
def accounts_inactive(request):
    """Return a list of the accounts that aren't activated."""
    user_list = UserMgr.get_list(active=False)
    ret = {
        'count': len(user_list),
        'users': [dict(h) for h in user_list],
    }
    return _api_response(request, ret)
Пример #13
0
def username_exists(username):
    user = UserMgr.get(username=username)

    response_dict = {}
    if user is None:
        response_dict['exists'] = False
    else:
        response_dict['exists'] = True
    return response_dict
Пример #14
0
def reset(request):
    """Once deactivated, allow for changing the password via activation key"""
    rdict = request.matchdict
    params = request.params

    # This is an initial request to show the activation form.
    username = rdict.get('username', None)
    activation_key = rdict.get('reset_key', None)
    user = ActivationMgr.get_user(username, activation_key)

    if user is None:
        # just 404 if we don't have an activation code for this user
        raise HTTPNotFound()

    if 'code' in params:
        # This is a posted form with the activation, attempt to unlock the
        # user's account.
        username = params.get('username', None)
        activation = params.get('code', None)
        password = params.get('new_password', None)
        new_username = params.get('new_username', None)
        error = None

        if not UserMgr.acceptable_password(password):
            # Set an error message to the template.
            error = "Come on, pick a real password please."
        else:
            res = ActivationMgr.activate_user(username, activation, password)
            if res:
                # success so respond nicely
                AuthLog.reactivate(username, success=True, code=activation)

                # if there's a new username and it's not the same as our current
                # username, update it
                if new_username and new_username != username:
                    try:
                        user = UserMgr.get(username=username)
                        user.username = new_username
                    except IntegrityError, exc:
                        error = 'There was an issue setting your new username'
            else:
                AuthLog.reactivate(username, success=False, code=activation)
                error = 'There was an issue attempting to activate this account.'
Пример #15
0
 def user(self):
     # <your database connection, however you get it, the below line
     # is just an example>
     # dbconn = self.registry.settings['dbconn']
     user_id = unauthenticated_userid(self)
     if user_id is not None:
         # this should return None if the user doesn't exist
         # in the database
         user = UserMgr.get(user_id=user_id)
         return user
Пример #16
0
 def __init__(self, activity, internal_task_id):
     self.activity = activity
     self.internal_task_id = internal_task_id # For tracking the status of the analysis
     self.summary_data = {}
     self.speed_graph = None
     root_dir = os.path.dirname(os.path.abspath(__file__))
     self.data_mgr = DataMgr.DataMgr(None, "file://" + root_dir, None, None, None)
     self.user_mgr = UserMgr.UserMgr(None)
     self.last_yield = time.time()
     super(ActivityAnalyzer, self).__init__()
Пример #17
0
 def __init__(self, user_id):
     self.user_id = user_id
     self.user_mgr = UserMgr.UserMgr(None)
     self.type = ""
     self.sport_type = ""
     self.scheduled_time = None  # The time at which this workout is to be performed
     self.warmup = {}  # The warmup interval
     self.cooldown = {}  # The cooldown interval
     self.intervals = []  # The workout intervals
     self.needs_rest_day_afterwards = False  # Used by the scheduler
     self.can_be_doubled = False  # Used by the scheduler to know whether or not this workout can be doubled up with other workouts
     self.workout_id = uuid.uuid4()  # Unique identifier for the workout
Пример #18
0
def reset(request):
    """Once deactivated, allow for changing the password via activation key"""
    rdict = request.matchdict
    params = request.params

    message = ''

    # This is an initial request to show the activation form.
    username = rdict.get('username', None)
    activation_key = rdict.get('reset_key', None)
    user = ActivationMgr.get_user(username, activation_key)

    if user is None:
        # just 404 if we don't have an activation code for this user
        raise HTTPNotFound()

    if 'code' in params:
        # This is a posted form with the activation, attempt to unlock the
        # user's account.
        username = params.get('username', None)
        activation = params.get('code', None)
        password1 = params.get('password1', None)
        password2 = params.get('password2', None)
        new_username = params.get('new_username', None)

        res = ActivationMgr.activate_user(username, activation, password1)
        if res:
            # success so respond nicely
            AuthLog.reactivate(username, success=True, code=activation)

            # if there's a new username and it's not the same as our current
            # username, update it
            if new_username and new_username != username:
                try:
                    user = UserMgr.get(username=username)
                    user.username = new_username
                except IntegrityError, exc:
                    message = 'There was an issue setting your new username. Please try again.'
        else:
            AuthLog.reactivate(username, success=False, code=activation)
            message = 'There was an issue attempting to activate this account.'

        if message is not '':
            return {
                'message': message,
                'user': user
            }
        else:
            # log the user out to have them re-login with the new password
            headers = forget(request)
            return HTTPFound(location=route_url('login', request),
                             headers=headers)
Пример #19
0
def user_list(request):
    """Provide list of users in the system.

    Supported Query params: order, limit
    """
    params = request.params
    order = params.get('order', None)
    limit = params.get('limit', None)
    user_list = UserMgr.get_list(order=order, limit=limit)
    ret = {
        'count': len(user_list),
        'users': [dict(h) for h in user_list],
    }
    return _api_response(request, ret)
Пример #20
0
Файл: api.py Проект: x4rMa/kifu
def reset_password(request):
    """Change a user's password from the current string

    :params current_password:
    :params new_password:

    Callable by either a logged in user or the api key for mobile apps/etc

    """

    params = request.params

    # now also load the password info
    current = params.get('current_password', None)
    new = params.get('new_password', None)

    # if we don't have any password info, try a json_body in case it's a json
    #POST
    if current is None and new is None:
        params = request.json_body
        current = params.get('current_password', None)
        new = params.get('new_password', None)

    user_acct = request.user

    LOG.error("PASSWD")
    LOG.error(current)
    LOG.error(new)
    if not UserMgr.acceptable_password(new):
        request.response.status_int = 406
        return _api_response(request, {
            'username': user_acct.username,
            'error': "Come on, let's try a real password this time"
        })

    # before we change the password, let's verify it
    if user_acct.validate_password(current):
        # we're good to change it
        user_acct.password = new
        request.response.status_int = 200
        return _api_response(request, {
            'username': user_acct.username,
            'message': "Password changed",
        })
    else:
        request.response.status_int = 403
        return _api_response(request, {
            'username': user_acct.username,
            'error': "There was a typo somewhere. Please check your request"
        })
Пример #21
0
Файл: api.py Проект: mazz/kifu
def user_list(request):
    """Provide list of users in the system.

    Supported Query params: order, limit
    """
    params = request.params
    order = params.get('order', None)
    limit = params.get('limit', None)
    user_list = UserMgr.get_list(order=order, limit=limit)
    ret = {
        'count': len(user_list),
        'users': [dict(h) for h in user_list],
    }
    return _api_response(request, ret)
Пример #22
0
def account(request):
    """Index of account page

    You can only load your own account page. If you try to view someone else's
    you'll just end up with your own.

    """
    # if auth fails, it'll raise an HTTPForbidden exception
    with ReqAuthorize(request):
        user = UserMgr.get(username=request.user.username)

        return {
            'user': user,
            'username': user.username,
        }
Пример #23
0
def signup_process(request):
    """Process the signup request

    If there are any errors drop to the same template with the error
    information.

    """
    if request.user and request.user.username:
        print("user logged in")
        return HTTPFound(location=request.route_url('user_account', username=request.user.username))
    else:
        signupForm = SignupForm(request.POST)

        if request.method == 'POST' and signupForm.validate():
            message = 'Thank you for signing up from: ' + str(signupForm.email.data) + '\nPlease check your email.'
            request.session.flash(message)

            #return HTTPFound(location=request.route_url('signup_process2'))
            new_user = UserMgr.signup_user(signupForm.email.data, 'signup')
            print "new_user: "******"Enable your account",
                   settings,
                   request.route_url(
                       'reset',
                       username=new_user.username,
                       reset_key=new_user.activation.code
                   )
                )

                # And let the user know they're signed up.
                return {'signup_success_message': message,
                        'form':signupForm,
                }

        return {'form':signupForm,
                'action':request.matchdict.get('action'),
                }
Пример #24
0
def check_for_ungenerated_workout_plans():
    """Checks for users that need their workout plan regenerated. Generates workout plans for each of those users."""
    now = datetime.datetime.utcnow()
    data_mgr = DataMgr.DataMgr(
        None, "", None, None,
        WorkoutPlanGeneratorScheduler.WorkoutPlanGeneratorScheduler())
    user_mgr = UserMgr.UserMgr(None)

    # These users don't have any pending workouts.
    user_ids = data_mgr.retrieve_users_without_scheduled_workouts()
    for user_id in user_ids:

        # Make sure we're not thrashing by only allowing workout generation once per day per user.
        last_gen_time = user_mgr.retrieve_user_setting(
            user_id, Keys.USER_PLAN_LAST_GENERATED_TIME)
        gen = (now - last_gen_time).total_seconds() > Units.SECS_PER_DAY
        if gen:
            data_mgr.generate_workout_plan_for_user(user_id)
            user_mgr.update_user_setting(user_id,
                                         Keys.USER_PLAN_LAST_GENERATED_TIME,
                                         now, now)
Пример #25
0
def check_for_unanalyzed_activities():
    """Check for activities that need to be analyzed. Do one, if any are found."""
    analysis_scheduler = AnalysisScheduler.AnalysisScheduler()
    data_mgr = DataMgr.DataMgr(None, "", analysis_scheduler, None, None)
    user_mgr = UserMgr.UserMgr(None)

    unanalyzed_activity_list = data_mgr.retrieve_unanalyzed_activity_list(64)
    if len(unanalyzed_activity_list) > 0:
        activity_id = str(random.choice(unanalyzed_activity_list))
        print("Selected " + activity_id + " for analysis.")
        complete_activity_data = data_mgr.retrieve_activity(activity_id)
        if complete_activity_data:
            activity_user_id = user_mgr.retrieve_user_from_activity(
                complete_activity_data)
            if activity_user_id:
                data_mgr.analyze_activity(complete_activity_data,
                                          activity_user_id)
            else:
                print("The activity owner could not be determined.")
        else:
            print("The activity could no be loaded.")
Пример #26
0
Файл: api.py Проект: mazz/kifu
def accounts_invites_add(request):
    """Set the number of invites a user has available.

    :matchdict username: The user to give these invites to.
    :matchdict count: The number of invites to give them.
    """
    rdict = request.matchdict
    username = rdict.get('username', None)
    count = rdict.get('count', None)

    if username is not None and count is not None:
        user = UserMgr.get(username=username)

        if user:
            user.invite_ct = count
            return _api_response(request, dict(user))
        else:
            request.response.status_int = 404
            ret = {'error': "Invalid user account."}
            return _api_response(request, ret)
    else:
        request.response.status_int = 400
        ret = {'error': "Bad request, missing parameters"}
        return _api_response(request, ret)
Пример #27
0
def accounts_invites_add(request):
    """Set the number of invites a user has available.

    :matchdict username: The user to give these invites to.
    :matchdict count: The number of invites to give them.
    """
    rdict = request.matchdict
    username = rdict.get('username', None)
    count = rdict.get('count', None)

    if username is not None and count is not None:
        user = UserMgr.get(username=username)

        if user:
            user.invite_ct = count
            return _api_response(request, dict(user))
        else:
            request.response.status_int = 404
            ret = {'error': "Invalid user account."}
            return _api_response(request, ret)
    else:
        request.response.status_int = 400
        ret = {'error': "Bad request, missing parameters"}
        return _api_response(request, ret)
Пример #28
0
def main():
    """Entry point for the flask version of the app."""
    global g_app
    global g_flask_app

    # Parse command line options.
    parser = argparse.ArgumentParser()
    parser.add_argument("--config",
                        type=str,
                        action="store",
                        default="",
                        help="The configuration file.",
                        required=False)

    try:
        args = parser.parse_args()
    except IOError as e:
        parser.error(e)
        sys.exit(1)

    config = Config.Config()
    if len(args.config) > 0:
        config.load(args.config)

    debug_enabled = config.is_debug_enabled()
    profiling_enabled = config.is_profiling_enabled()
    host = config.get_hostname()
    hostport = config.get_hostport()
    googlemaps_key = config.get_google_maps_key()

    if config.is_https_enabled():
        protocol = "https"
    else:
        protocol = "http"

    if len(host) == 0:
        if debug_enabled:
            host = "127.0.0.1"
        else:
            host = "openworkout.cloud"
        print("Hostname not provided, will use " + host)

    root_url = protocol + "://" + host
    if hostport > 0:
        root_url = root_url + ":" + str(hostport)
    print("Root URL is " + root_url)

    signal.signal(signal.SIGINT, signal_handler)
    mako.collection_size = 100
    mako.directories = "templates"

    session_mgr = SessionMgr.FlaskSessionMgr()
    user_mgr = UserMgr.UserMgr(session_mgr)
    analysis_scheduler = AnalysisScheduler.AnalysisScheduler()
    import_scheduler = ImportScheduler.ImportScheduler()
    workout_plan_gen = WorkoutPlanGeneratorScheduler.WorkoutPlanGeneratorScheduler(
    )
    data_mgr = DataMgr.DataMgr(config, root_url, analysis_scheduler,
                               import_scheduler, workout_plan_gen)
    g_app = App.App(user_mgr, data_mgr, g_root_dir, root_url, googlemaps_key,
                    profiling_enabled, debug_enabled)

    logging.basicConfig(filename=ERROR_LOG,
                        filemode='w',
                        level=logging.DEBUG,
                        format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p')

    # The markdown library is kinda spammy.
    markdown_logger = logging.getLogger("MARKDOWN")
    markdown_logger.setLevel(logging.ERROR)

    g_flask_app.run(host=config.get_bindname(),
                    port=config.get_bindport(),
                    debug=debug_enabled)
Пример #29
0
Файл: api.py Проект: mazz/kifu
def invite_user(request):
    """Invite a new user into the system.

    :param username: user that is requested we invite someone
    :param email: email address of the new user

    """
    params = request.params

    email = params.get('email', None)
    user = request.user

    if not email:
        # try to get it from the json body
        email = request.json_body.get('email', None)

    if not email:
        # if still no email, I give up!
        request.response.status_int = 406
        return _api_response(request, {
            'username': user.username,
            'error': "Please submit an email address"
        })

    # first see if the user is already in the system
    exists = UserMgr.get(email=email)
    if exists:
        request.response.status_int = 406
        return _api_response(request, {
            'username': exists.username,
            'error': "This user is already a user!"
        })

    new_user = user.invite(email)
    if new_user:
        LOG.error(new_user.username)
        # then this user is able to invite someone
        # log it
        AuthLog.reactivate(new_user.username)

        # and then send an email notification
        # @todo the email side of things
        settings = request.registry.settings
        msg = InvitationMsg(new_user.email,
                            "Enable your account",
                            settings)

        msg.send(
            request.route_url(
                'reset',
                username=new_user.username,
                reset_key=new_user.activation.code))
        return _api_response(request, {
            'message': 'You have invited: ' + new_user.email
        })
    else:
        # you have no invites
        request.response.status_int = 406
        return _api_response(request, {
            'username': user.username,
            'error': "You have no invites left at this time."
        })
Пример #30
0
def main():
    """Entry point for the cherrypy version of the app."""
    global g_app

    # Parse command line options.
    parser = argparse.ArgumentParser()
    parser.add_argument("--config",
                        type=str,
                        action="store",
                        default="",
                        help="The configuration file.",
                        required=False)

    try:
        args = parser.parse_args()
    except IOError as e:
        parser.error(e)
        sys.exit(1)

    config = Config.Config()
    if len(args.config) > 0:
        config.load(args.config)

    debug_enabled = config.is_debug_enabled()
    profiling_enabled = config.is_profiling_enabled()
    host = config.get_hostname()
    hostport = config.get_hostport()
    googlemaps_key = config.get_google_maps_key()

    if config.is_https_enabled():
        cert_file = config.get_certificate_file()
        privkey_file = config.get_private_key_file()
        print("Running HTTPS....")
        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = cert_file
        print("Certificate File: " + cert_file)
        cherrypy.server.ssl_private_key = privkey_file
        print("Private Key File: " + privkey_file)
        protocol = "https"
    else:
        protocol = "http"

    if len(host) == 0:
        if debug_enabled:
            host = "127.0.0.1"
        else:
            host = "openworkout.cloud"
        print("Hostname not provided, will use " + host)

    root_dir = os.path.dirname(os.path.abspath(__file__))
    root_url = protocol + "://" + host
    if hostport > 0:
        root_url = root_url + ":" + str(hostport)
    print("Root URL is " + root_url)

    if not debug_enabled:
        Daemonizer(cherrypy.engine).subscribe()

    # Register the signal handler.
    signal.signal(signal.SIGINT, signal_handler)

    # Configure the template engine.
    mako.collection_size = 100
    mako.directories = "templates"

    session_mgr = SessionMgr.CherryPySessionMgr()
    user_mgr = UserMgr.UserMgr(session_mgr)
    analysis_scheduler = AnalysisScheduler.AnalysisScheduler()
    import_scheduler = ImportScheduler.ImportScheduler()
    workout_plan_gen = WorkoutPlanGeneratorScheduler.WorkoutPlanGeneratorScheduler(
    )
    data_mgr = DataMgr.DataMgr(config, root_url, analysis_scheduler,
                               import_scheduler, workout_plan_gen)
    backend = App.App(user_mgr, data_mgr, root_dir, root_url, googlemaps_key,
                      profiling_enabled, debug_enabled)
    g_app = CherryPyFrontEnd(backend)

    # Configure the error logger.
    logging.basicConfig(filename=ERROR_LOG,
                        filemode='w',
                        level=logging.DEBUG,
                        format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p')

    # The markdown library is kinda spammy.
    markdown_logger = logging.getLogger("MARKDOWN")
    markdown_logger.setLevel(logging.ERROR)

    # The direcory for session objects.
    if sys.version_info[0] < 3:
        session_dir = os.path.join(root_dir, 'sessions2')
    else:
        session_dir = os.path.join(root_dir, 'sessions3')
    if not os.path.exists(session_dir):
        os.makedirs(session_dir)

    cherrypy.tools.web_auth = cherrypy.Tool('before_handler', do_auth_check)

    conf = {
        '/': {
            'tools.staticdir.root': root_dir,
            'tools.web_auth.on': True,
            'tools.sessions.on': True,
            'tools.sessions.httponly': True,
            'tools.sessions.name': 'web_auth',
            'tools.sessions.storage_type': 'file',
            'tools.sessions.storage_path': session_dir,
            'tools.sessions.timeout': 129600,
            'tools.sessions.locking': 'early',
            'tools.secureheaders.on': True
        },
        '/api': {
            'tools.response_headers.on':
            True,
            'tools.response_headers.headers':
            [('Access-Control-Allow-Origin', '*')],
        },
        '/css': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'css'
        },
        '/data': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'data'
        },
        '/js': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'js'
        },
        '/jquery-timepicker': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'jquery-timepicker'
        },
        '/images': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'images',
        },
        '/media': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'media',
        },
        '/photos': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'photos',
        },
        '/.well-known': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.well-known',
        },
    }

    cherrypy.config.update({
        'server.socket_host': config.get_bindname(),
        'server.socket_port': config.get_bindport(),
        'requests.show_tracebacks': False,
        'error_page.404': g_app.error_404,
        'log.access_file': ACCESS_LOG
    })

    reload_feature = ReloadFeature(cherrypy.engine)
    reload_feature.subscribe()

    cherrypy.quickstart(g_app, config=conf)
Пример #31
0
def invite_user(request):
    """Invite a new user into the system.

    :param username: user that is requested we invite someone
    :param email: email address of the new user

    """
    params = request.params

    email = params.get('email', None)
    user = request.user

    if not email:
        # try to get it from the json body
        email = request.json_body.get('email', None)

    if not email:
        # if still no email, I give up!
        request.response.status_int = 406
        return _api_response(request, {
            'username': user.username,
            'error': "Please submit an email address"
        })

    # first see if the user is already in the system
    exists = UserMgr.get(email=email)
    if exists:
        request.response.status_int = 406
        return _api_response(request, {
            'username': exists.username,
            'error': "This user is already a user!"
        })

    new_user = user.invite(email)
    if new_user:
        LOG.error(new_user.username)
        # then this user is able to invite someone
        # log it
        AuthLog.reactivate(new_user.username)

        # and then send an email notification
        # @todo the email side of things
        settings = request.registry.settings
        msg = InvitationMsg(new_user.email,
                            "Enable your account",
                            settings)

        msg.send(
            request.route_url(
                'reset',
                username=new_user.username,
                reset_key=new_user.activation.code))
        return _api_response(request, {
            'message': 'You have invited: ' + new_user.email
        })
    else:
        # you have no invites
        request.response.status_int = 406
        return _api_response(request, {
            'username': user.username,
            'error': "You have no invites left at this time."
        })
Пример #32
0
def is_already_taken(form, field):
    if not field.data:
        raise ValidationError('Insert your email')
    exists = UserMgr.get(email=field.data)
    if exists:
        raise ValidationError('The user has already signed up.')
Пример #33
0
def main():
    """Entry point for the flask version of the app."""
    global g_app
    global g_flask_app

    # Parse command line options.
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--debug",
        action="store_true",
        default=False,
        help="Prevents the app from going into the background.",
        required=False)
    parser.add_argument("--profile",
                        action="store_true",
                        default=False,
                        help="Enables application profiling.",
                        required=False)
    parser.add_argument(
        "--host",
        default="",
        help="Host name on which users will access this website.",
        required=False)
    parser.add_argument("--hostport",
                        type=int,
                        default=5000,
                        help="Port on which users will access this website.",
                        required=False)
    parser.add_argument("--https",
                        action="store_true",
                        default=False,
                        help="Runs the app as HTTPS.",
                        required=False)
    parser.add_argument(
        "--googlemapskey",
        default="",
        help=
        "API key for Google Maps. If not provided OpenStreetMap will be used.",
        required=False)

    try:
        args = parser.parse_args()
    except IOError as e:
        parser.error(e)
        sys.exit(1)

    if args.https:
        protocol = "https"
    else:
        protocol = "http"

    if len(args.host) == 0:
        if args.debug:
            args.host = "127.0.0.1"
        else:
            args.host = "straen-app.com"
        print("Hostname not provided, will use " + args.host)

    root_url = protocol + "://" + args.host
    if args.hostport > 0:
        root_url = root_url + ":" + str(args.hostport)
    print("Root URL is " + root_url)

    signal.signal(signal.SIGINT, signal_handler)
    mako.collection_size = 100
    mako.directories = "templates"

    session_mgr = SessionMgr.FlaskSessionMgr()
    user_mgr = UserMgr.UserMgr(session_mgr)
    data_mgr = DataMgr.DataMgr(
        root_url, AnalysisScheduler.AnalysisScheduler(),
        ImportScheduler.ImportScheduler(),
        WorkoutPlanGeneratorScheduler.WorkoutPlanGeneratorScheduler())
    g_app = App.App(user_mgr, data_mgr, g_root_dir, root_url,
                    args.googlemapskey, args.profile, args.debug)

    logging.basicConfig(filename=ERROR_LOG,
                        filemode='w',
                        level=logging.DEBUG,
                        format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p')

    # The markdown library is kinda spammy.
    markdown_logger = logging.getLogger("MARKDOWN")
    markdown_logger.setLevel(logging.ERROR)

    g_flask_app.run(debug=args.debug)
Пример #34
0
def signup(request):
    """Process the signup request

    If there are any errors drop to the same template with the error
    information.

    """

    message = ''

    # import pdb; pdb.set_trace()
    if request.user and request.user.username:
        print("user logged in")
        return HTTPFound(location=request.route_url('user_account', username=request.user.username))
    else:
        if request.method == 'POST':
            email = request.params['email']
            # password = request.params['password']

            LOG.debug(email)
            auth = UserMgr.get(email=email)

            if auth and auth.activated:
                return {
                    'email': '',
                    'message': 'A user with this email already exists.',
                }
            else:
                if auth and auth.activated is not True:
                    message = 'Re-sending another signup to: ' + str(email) + '\nPlease check your email.'
                else:
                    message = 'Thank you for signing up from: ' + str(email) + '\nPlease check your email.'

            request.session.flash(message)

            #return HTTPFound(location=request.route_url('signup_process2'))
            new_user = UserMgr.signup_user(email, 'signup')
            print "new_user: "******"Enable your account",
                   settings,
                   request.route_url(
                       'reset',
                       username=new_user.username,
                       reset_key=new_user.activation.code
                   )
                )

                # And let the user know they're signed up.
                return {'message': message,
                        'email':email,
                }

        return {'email': '',
                'message': message,
                }
Пример #35
0
def forgot_password(request):
    """Login the user to the system

    If not POSTed then show the form
    If error, display the form with the error message
    If successful, forward the user to their /recent

    Note: the came_from stuff we're not using atm. We'll clean out if we keep
    things this way

    """
    # in case they're already logged-in just send them to their profile page for now
    if request.user:
        headers = remember(request, request.user.id, max_age=max_cookie_age)
        return HTTPFound(location=request.route_url('user_account', username=request.user.username),headers=headers)

    fp_url = route_url('forgot_password', request)
    referrer = request.url
    if referrer == fp_url:
        referrer = '/'  # never use the login form itself as came_from
    came_from = request.params.get('came_from', referrer)
    #
    message = ''
    # login = ''
    # password = ''

    # import pdb; pdb.set_trace()

    if 'form.submitted' in request.params:
        email = request.params['email']
        # password = request.params['password']

        LOG.debug(email)
        user = UserMgr.get(email=email)
        LOG.debug(user)
        # LOG.debug(UserMgr.get_list())

        settings = request.registry.settings

        if user:
            # Add a queue job to send the user a notification email.
            user.reactivate('forgot_password')
            tasks.email_forgot_password_user.delay(
                user.email,
                "Reset Your Password",
                settings,
                request.route_url(
                'reset',
                username=user.username,
                reset_key=user.activation.code)
            )

            message = 'An email has been sent with instructions for resetting your password. If you do not receive it within an hour or two, check your spam folder.'
            # # We use the Primary Key as our identifier once someone has
            # # authenticated rather than the username.  You can change what is
            # # returned as the userid by altering what is passed to remember.
            # headers = remember(request, auth.id, max_age=60 * 60 * 24 * 30)
            # auth.last_login = datetime.utcnow()
            #
            # # log the successful login
            # AuthLog.login(login, True)

            # we're always going to return a user to their own /recent after a
            # login
#             return HTTPFound(
#                 location=request.route_url(
#                     'user_bmark_recent',
#                     username=auth.username),
#                 headers=headers)

            # return HTTPFound(
            #     location=request.route_url(
            #         'forgot_password_email_confirmed'),
            #     headers=headers)

        if not user:
            message = 'There was an error attempting to find that email.'
        # log the right level of problem
        # if auth and not auth.validate_password(password):
        #     message = "Your login attempt has failed."
        #     AuthLog.login(login, False, password=password)
        #
        # elif auth and not auth.activated:
        #     message = "User account deactivated. Please check your email."
        #     AuthLog.login(login, False, password=password)
        #     AuthLog.disabled(login)
        #
        # elif auth is None:
        #     message = "Failed login"
        #     AuthLog.login(login, False, password=password)
    return {
        'message': message,
        'came_from': came_from,
    }
Пример #36
0
 def __init__(self, user_id):
     self.user_id = user_id
     self.user_mgr = UserMgr.UserMgr(None)
Пример #37
0
def login(request):
    """Login the user to the system

    If not POSTed then show the form
    If error, display the form with the error message
    If successful, forward the user to their /recent

    Note: the came_from stuff we're not using atm. We'll clean out if we keep
    things this way

    """

    # in case they're already logged-in just send them to their profile page for now
    if request.user:
        headers = remember(request, request.user.id, max_age=max_cookie_age)
        return HTTPFound(location=request.route_url('user_account', username=request.user.username),headers=headers)

    login_url = route_url('login', request)
    referrer = request.url
    if referrer == login_url:
        referrer = '/'  # never use the login form itself as came_from

    came_from = request.params.get('came_from', referrer)

    message = ''
    email = ''
    password = ''
    headers = None

    # import pdb; pdb.set_trace()

    if 'form.submitted' in request.params:
        email = request.params['email']
        password = request.params['password']

        LOG.debug(email)
        auth = UserMgr.get(email=email)
        LOG.debug(auth)
        LOG.debug(UserMgr.get_list())

        if auth and auth.validate_password(password) and auth.activated:
            # We use the Primary Key as our identifier once someone has
            # authenticated rather than the username.  You can change what is
            # returned as the userid by altering what is passed to remember.
            headers = remember(request, auth.id, max_age=max_cookie_age)
            auth.last_login = datetime.utcnow()

            # log the successful login
            AuthLog.login(auth.username, True)

            # we're always going to return a user to their own /recent after a
            # login
#             return HTTPFound(
#                 location=request.route_url(
#                     'user_bmark_recent',
#                     username=auth.username),
#                 headers=headers)

            return HTTPFound(
                location=request.route_url(
                    'user_account',
                    username=auth.username),
                headers=headers)

        # log the right level of problem
        if auth and not auth.validate_password(password):
            message = "Your login attempt has failed."
            AuthLog.login(email, False, password=password)

        elif auth and not auth.activated:
            message = "User account deactivated. Please check your email."
            AuthLog.login(email, False, password=password)
            AuthLog.disabled(email)

        elif auth is None:
            message = "Failed login"
            AuthLog.login(email, False, password=password)

    # in case they're already logged-in just send them to their profile page for now
    if request.user:
        headers = remember(request, request.user.id, max_age=max_cookie_age)
        return HTTPFound(
            location=request.route_url(
                'user_account',
                username=request.user.username),
            headers=headers)

    return {
        'message': message,
        'came_from': came_from,
        'email': email,
        'password': password,
    }