Ejemplo n.º 1
0
def _send_login_email(user, uri):
    global _smtp
    if not _smtp:
        if not (pkconfig.channel_in('dev')
                and cfg.smtp_server == _DEV_SMTP_SERVER):
            a = sirepo.util.flask_app()
            a.config.update(
                MAIL_USE_TLS=True,
                MAIL_PORT=587,
                MAIL_SERVER=cfg.smtp_server,
                MAIL_USERNAME=cfg.smtp_user,
                MAIL_PASSWORD=cfg.smtp_password,
            )
            _smtp = flask_mail.Mail(a)
        else:
            pkdlog('{}', uri)
            return http_reply.gen_json_ok({'uri': uri})
    login_text = u'sign in to' if user.user_name else \
        u'confirm your email and finish creating'
    msg = flask_mail.Message(subject='Sign in to Sirepo',
                             sender=(cfg.from_name, cfg.from_email),
                             recipients=[user.unverified_email],
                             body=u'''
Click the link below to {} your Sirepo account.

This link will expire in {} hours and can only be used once.

{}
'''.format(login_text, _EXPIRES_MINUTES / 60, uri))
    _smtp.send(msg)
    return http_reply.gen_json_ok()
Ejemplo n.º 2
0
def api_updateFolder():
    #TODO(robnagler) Folder should have a serial, or should it be on data
    req = http_request.parse_post()
    o = srschema.parse_folder(req.req_data['oldName'])
    if o == '/':
        raise sirepo.util.Error(
            'cannot rename root ("/") folder',
            'old folder is root req={}',
            req,
        )
    n = srschema.parse_folder(req.req_data['newName'])
    if n == '/':
        raise sirepo.util.Error(
            'cannot rename folder to root ("/")',
            'new folder is root req={}',
            req,
        )
    for r in simulation_db.iterate_simulation_datafiles(
            req.type, _simulation_data_iterator):
        f = r.models.simulation.folder
        l = o.lower()
        if f.lower() == o.lower():
            r.models.simulation.folder = n
        elif f.lower().startswith(o.lower() + '/'):
            r.models.simulation.folder = n + f[len():]
        else:
            continue
        simulation_db.save_simulation_json(r)
    return http_reply.gen_json_ok()
Ejemplo n.º 3
0
def api_comsolRegister():
    import flask
    import flask_mail
    import sirepo.util

    global _mail
    if not _mail:
        a = sirepo.util.flask_app()
        a.config.update(
            MAIL_USE_TLS=True,
            MAIL_PORT=587,
            MAIL_SERVER=cfg.mail_server,
            MAIL_USERNAME=cfg.mail_username,
            MAIL_PASSWORD=cfg.mail_password,
        )
        _mail = flask_mail.Mail(a)
    req = http_request.parse_json()
    msg = flask_mail.Message(
        subject='Sirepo / COMSOL Registration',
        sender=cfg.mail_support_email,
        recipients=[cfg.mail_recipient_email],
        body=u'''
Request for access to Sirepo / COMSOL.

Name: {}
Email: {}
'''.format(req.name, req.email),
    )
    _mail.send(msg)
    return http_reply.gen_json_ok()
Ejemplo n.º 4
0
def _send_login_email(user, uri):
    login_text = u'sign in to' if user.user_name else \
        u'confirm your email and finish creating'
    r = smtp.send(recipient=user.unverified_email,
                  subject='Sign in to Sirepo',
                  body=u'''
Click the link below to {} your Sirepo account.

This link will expire in {} hours and can only be used once.

{}
'''.format(login_text, _EXPIRES_MINUTES / 60, uri))
    if not r:
        pkdlog('{}', uri)
        return http_reply.gen_json_ok({'uri': uri})
    return http_reply.gen_json_ok()
Ejemplo n.º 5
0
def api_authCompleteRegistration():
    # Needs to be explicit, because we would need a special permission
    # for just this API.
    if not _is_logged_in():
        raise util.SRException(LOGIN_ROUTE_NAME, None)
    complete_registration(
        _parse_display_name(http_request.parse_json().get('displayName')), )
    return http_reply.gen_json_ok()
Ejemplo n.º 6
0
def api_srUnit():
    v = getattr(flask.current_app, SRUNIT_TEST_IN_REQUEST)
    if v.want_user:
        import sirepo.auth
        sirepo.auth.set_user_for_utils()
    if v.want_cookie:
        import sirepo.cookie
        sirepo.cookie.set_sentinel()
    v.op()
    return http_reply.gen_json_ok()
Ejemplo n.º 7
0
def _send_login_email(user, url):
    if not _smtp:
        assert pkconfig.channel_in('dev')
        pkdlog('{}', url)
        return http_reply.gen_json_ok({'url': url})
    login_text = u'sign in to' if user.user_name else \
        u'confirm your email and finish creating'
    msg = flask_mail.Message(subject='Sign in to Sirepo',
                             sender=(cfg.from_name, cfg.from_email),
                             recipients=[user.unverified_email],
                             body=u'''
Click the link below to {} your Sirepo account.

This link will expire in {} hours and can only be used once.

{}
'''.format(login_text, _EXPIRES_MINUTES / 60, url))
    _smtp.send(msg)
    return http_reply.gen_json_ok()
Ejemplo n.º 8
0
def api_updateFolder():
    #TODO(robnagler) Folder should have a serial, or should it be on data
    data = _parse_data_input()
    old_name = data['oldName']
    new_name = data['newName']
    for row in simulation_db.iterate_simulation_datafiles(data['simulationType'], _simulation_data):
        folder = row['models']['simulation']['folder']
        if folder.startswith(old_name):
            row['models']['simulation']['folder'] = re.sub(re.escape(old_name), new_name, folder, 1)
            simulation_db.save_simulation_json(row)
    return http_reply.gen_json_ok()
Ejemplo n.º 9
0
def api_srUnit():
    import sirepo.auth
    import sirepo.cookie
    v = getattr(sirepo.util.flask_app(), SRUNIT_TEST_IN_REQUEST)
    u = contextlib.nullcontext
    if v.want_user:
        sirepo.cookie.set_sentinel()
        sirepo.auth.login(sirepo.auth.guest, is_mock=True)
    if v.want_cookie:
        sirepo.cookie.set_sentinel()
    v.op()
    return http_reply.gen_json_ok()
Ejemplo n.º 10
0
def api_serverStatus():
    """Allow for remote monitoring of the web server status.

    The user must be an existing sirepo uid.  The status checks
    that a simple simulation can complete successfully within a
    short period of time.
    """
    _run_tests()
    return http_reply.gen_json_ok({
        'datetime':
        datetime.datetime.utcnow().isoformat(),
    })
Ejemplo n.º 11
0
def api_adjustTime(days=None):
    """Shift the system time by days and get the adjusted time

    Args:
        days (str): must be integer. If None or 0, no adjustment.
    """
    from sirepo import http_reply

    adjust_time(days)
    return http_reply.gen_json_ok({
        'adjustedNow': utc_now().isoformat(),
        'systemNow': datetime.datetime.utcnow().isoformat(),
    })
Ejemplo n.º 12
0
def api_deleteFile():
    req = http_request.parse_post(filename=True, file_type=True)
    e = _simulations_using_file(req)
    if len(e):
        return http_reply.gen_json({
            'error': 'File is in use in other simulations.',
            'fileList': e,
            'fileName': req.filename,
        })

    # Will not remove resource (standard) lib files
    pkio.unchecked_remove(_lib_file_write_path(req))
    return http_reply.gen_json_ok()
Ejemplo n.º 13
0
def login_success_response(sim_type, want_redirect=False):
    r = None
    if (cookie.get_value(_COOKIE_STATE) == _STATE_COMPLETE_REGISTRATION
            and cookie.get_value(_COOKIE_METHOD) == METHOD_GUEST):
        complete_registration()
    if want_redirect:
        r = 'completeRegistration' if (
            cookie.get_value(_COOKIE_STATE)
            == _STATE_COMPLETE_REGISTRATION) else None
        raise sirepo.util.Redirect(
            sirepo.uri.local_route(sim_type, route_name=r))
    raise sirepo.util.Response(response=http_reply.gen_json_ok(
        PKDict(authState=_auth_state())), )
Ejemplo n.º 14
0
def api_blueskyAuth():
    req = http_request.parse_json()
    auth_hash(req, verify=True)
    sid = req.simulationId
    sim_type = req.simulationType
    path = simulation_db.find_global_simulation(
        sim_type,
        sid,
        checked=True,
    )
    cookie.set_user(simulation_db.uid_from_dir_name(path))
    return http_reply.gen_json_ok(dict(
        data=simulation_db.open_json_file(req.simulationType, sid=req.simulationId),
        schema=simulation_db.get_schema(req.simulationType),
    ))
Ejemplo n.º 15
0
def api_comsolRegister():
    req = http_request.parse_json()
    msg = flask_mail.Message(
        subject='Sirepo / COMSOL Registration',
        sender=cfg.mail_support_email,
        recipients=[cfg.mail_recipient_email],
        body=u'''
Request for access to Sirepo / COMSOL.

Name: {}
Email: {}
'''.format(req.name, req.email),
    )
    _mail.send(msg)
    return http_reply.gen_json_ok()
Ejemplo n.º 16
0
def api_comsolRegister():
    import sirepo.util

    req = http_request.parse_json()
    smtp.send(
        recipient=cfg.mail_recipient_email,
        subject='Sirepo / COMSOL Registration',
        body=u'''
Request for access to Sirepo / COMSOL.

Name: {}
Email: {}
'''.format(req.name, req.email),
    )
    return http_reply.gen_json_ok()
Ejemplo n.º 17
0
def api_comsolRegister():
    req = http_request.parse_json()
    msg = flask_mail.Message(
        subject='Sirepo / COMSOL Registration',
        sender=cfg.mail_support_email,
        recipients=[cfg.mail_recipient_email],
        body=u'''
Request for access to Sirepo / COMSOL.

Name: {}
Email: {}
'''.format(req.name, req.email),
    )
    _mail.send(msg)
    return http_reply.gen_json_ok()
Ejemplo n.º 18
0
def api_authCompleteRegistration():
    # Needs to be explicit, because we would need a special permission
    # for just this API.
    if not _is_logged_in():
        return http_reply.gen_sr_exception(LOGIN_ROUTE_NAME)
    d = http_request.parse_json()
    t = d.simulationType
    n = _parse_display_name(d)
    u = _get_user()
    with auth_db.thread_lock:
        r = _user_registration(u)
        r.display_name = n
        r.save()
    cookie.set_value(_COOKIE_STATE, _STATE_LOGGED_IN)
    return http_reply.gen_json_ok()
Ejemplo n.º 19
0
def api_errorLogging():
    ip = flask.request.remote_addr
    try:
        pkdlog(
            '{}: javascript error: {}',
            ip,
            simulation_db.generate_json(http_request.parse_json(), pretty=True),
        )
    except ValueError as e:
        pkdlog(
            '{}: error parsing javascript app_error: {} input={}',
            ip,
            e,
            flask.request.data.decode('unicode-escape'),
        )
    return http_reply.gen_json_ok()
Ejemplo n.º 20
0
def api_blueskyAuth():
    req = http_request.parse_json()
    auth_hash(req, verify=True)
    sid = req.simulationId
    sim_type = req.simulationType
    path = simulation_db.find_global_simulation(
        sim_type,
        sid,
        checked=True,
    )
    cookie.set_user(simulation_db.uid_from_dir_name(path))
    return http_reply.gen_json_ok(
        dict(
            data=simulation_db.open_json_file(req.simulationType,
                                              sid=req.simulationId),
            schema=simulation_db.get_schema(req.simulationType),
        ))
Ejemplo n.º 21
0
def api_serverStatus():
    """Allow for remote monitoring of the web server status. Authentication
    is done via Basic Auth. The username should be an existing sirepo uid.
    The status checks that a simple simulation can complete successfully
    within a short period of time.
    """
    if not _basic_auth.authenticate():
        return _basic_auth.challenge()
    uid = flask.request.authorization.username
    simulation_db.assert_id(uid)
    if not simulation_db.user_dir_name(uid).exists():
        raise RuntimeError('status user does not exist: {}'.format(uid))
    cookie.set_user(uid)
    _run_tests()
    return http_reply.gen_json_ok({
        'datetime':
        datetime.datetime.utcnow().isoformat(),
    })
Ejemplo n.º 22
0
def api_authBlueskyLogin():
    req = http_request.parse_json()
    auth_hash(req, verify=True)
    sid = req.simulationId
    sim_type = req.simulationType
    path = simulation_db.find_global_simulation(
        sim_type,
        sid,
        checked=True,
    )
    r = auth.login(
        this_module,
        uid=simulation_db.uid_from_dir_name(path),
    )
    if r:
        return r
    return http_reply.gen_json_ok(dict(
        data=simulation_db.open_json_file(req.simulationType, sid=req.simulationId),
        schema=simulation_db.get_schema(req.simulationType),
    ))
Ejemplo n.º 23
0
def api_deleteSimulation():
    req = http_request.parse_post(id=True)
    simulation_db.delete_simulation(req.type, req.id)
    return http_reply.gen_json_ok()
Ejemplo n.º 24
0
def api_deleteSimulation():
    data = _parse_data_input()
    simulation_db.delete_simulation(data['simulationType'],
                                    data['simulationId'])
    return http_reply.gen_json_ok()