Exemplo n.º 1
0
def user_page(uid, nickname=None):
    user = User(uid=uid).get()

    if not user:
        return u'', 200

    oauth = OAuth(user['mail']).get()

    if 'profile' in user and 'badge_name' in user['profile']:
        _nickname = user['profile']['badge_name']
    else:
        _nickname = oauth['data']['name']

    _nickname = quote_plus(_nickname)

    if nickname is None or nickname != _nickname:
        return redirect(url_for('user.user_page', uid=uid, nickname=_nickname))

    if 'profile' not in user:
        badge_name = ''
        intro = ''
    else:
        badge_name = user['profile']['badge_name']
        intro = re.sub('<a href="javascript:.*"', '<a href="/"',
                       markdown(html.escape(user['profile']['intro'])))

    participate_in = []
    for p in Team.participate_in(uid):
        p['_project'] = Project.get(p['pid'])
        p['_title'] = '???'
        if uid in p['chiefs']:
            p['_title'] = 'chief'
        elif uid in p['members']:
            p['_title'] = 'member'

        p['_action_date'] = arrow.get(
            p['_project']['action_date']).format('YYYY/MM')

        participate_in.append(p)

    participate_in = sorted(participate_in,
                            key=lambda p: p['_project']['action_date'],
                            reverse=True)

    mattermost_data = {}
    mid = MattermostTools.find_possible_mid(uid=uid)
    if mid:
        mattermost_data['mid'] = mid
        mattermost_data['username'] = MattermostTools.find_user_name(mid=mid)

    return render_template(
        './user.html',
        badge_name=badge_name,
        intro=intro,
        oauth=oauth,
        user=user,
        mattermost_data=mattermost_data,
        participate_in=participate_in,
    )
Exemplo n.º 2
0
def index():
    if 'user' not in g:
        return render_template('index.html')

    check = {
        'profile': False,
        'participate_in': False,
        'mattermost': False,
    }

    if 'profile' in g.user['account'] and 'intro' in g.user['account'][
            'profile']:
        if len(g.user['account']['profile']['intro']) > 100:
            check['profile'] = True

    if list(Team.participate_in(uid=g.user['account']['_id'])):
        check['participate_in'] = True

    if MattermostTools.find_possible_mid(uid=g.user['account']['_id']):
        check['mattermost'] = True

    return render_template('index_guide.html', check=check)
Exemplo n.º 3
0
def project(pid):
    ''' Project '''
    # pylint: disable=too-many-locals,too-many-return-statements,too-many-branches,too-many-statements
    uid = g.get('user', {}).get('account', {}).get('_id')

    project_info = Project.get(pid=pid)
    if not project_info:
        return '404', 404

    is_in_project = False
    if uid:
        is_in_project = bool(Team.participate_in(uid, pid))

    if request.method == 'GET':
        return render_template('./tasks_project.html', project=project_info)

    if request.method == 'POST':
        post_data = request.get_json()

        def page_args(data, uid):
            data['_uid'] = uid
            data['_joined'] = False
            data['_login'] = False
            data['_is_in_project'] = is_in_project

            if uid:
                data['_login'] = True

                if uid in data['people']:
                    data['_joined'] = True

        if post_data['casename'] == 'get':
            datas = []

            for data in Tasks.get_by_pid(pid=pid):
                page_args(data=data, uid=uid)
                datas.append(data)

            is_star = False
            if uid:
                is_star = TasksStar.status(pid, uid)['add']

            return jsonify({
                'datas': datas,
                'is_in_project': is_in_project,
                'is_star': is_star
            })

        if post_data['casename'] == 'star':
            if not uid:
                return jsonify({'info': 'Need login'}), 401

            result = TasksStar.toggle(pid=pid, uid=uid)

            return jsonify({'is_star': result['add']})

        if post_data['casename'] == 'join':
            if not uid:
                return jsonify({'info': 'Need login'}), 401

            data = Tasks.join(pid=pid, task_id=post_data['task_id'], uid=uid)
            page_args(data=data, uid=uid)

            return jsonify({'data': data})

        if post_data['casename'] == 'cancel':
            if not uid:
                return jsonify({'info': 'Need login'}), 401

            data = Tasks.cancel(pid=pid, task_id=post_data['task_id'], uid=uid)
            page_args(data=data, uid=uid)

            return jsonify({'data': data})

        if post_data['casename'] == 'cancel_user':
            if not uid:
                return jsonify({'info': 'Need login'}), 401

            if not is_in_project:
                return jsonify({'info': 'Need as staff'}), 401

            data = Tasks.cancel(pid=pid,
                                task_id=post_data['task_id'],
                                uid=post_data['uid'])
            page_args(data=data, uid=uid)

            return jsonify({'data': data})

        if post_data['casename'] == 'peoples':
            task_data = Tasks.get_with_pid(pid=pid, _id=post_data['task_id'])
            if not task_data:
                return jsonify({}), 404

            creator = {}
            if task_data:
                user_info = User.get_info(uids=[
                    task_data['created_by'],
                ])
                creator['name'] = user_info[
                    task_data['created_by']]['profile']['badge_name']
                creator['uid'] = task_data['created_by']

                mid = MattermostTools.find_possible_mid(
                    uid=task_data['created_by'])
                if mid:
                    creator['mattermost_uid'] = MattermostTools.find_user_name(
                        mid=mid)

            if not is_in_project:
                return jsonify({'peoples': {}, 'creator': creator})

            users_info = Tasks.get_peoples_info(pid=pid,
                                                task_id=post_data['task_id'])
            peoples = {}
            for uid, user in users_info.items():
                peoples[uid] = {
                    'name': user['profile']['badge_name'],
                    'mail': user['oauth']['email'],
                    'picture': user['oauth']['picture'],
                    'mattermost_uid': None,
                }

                mid = MattermostTools.find_possible_mid(uid=uid)
                if mid:
                    peoples[uid][
                        'mattermost_uid'] = MattermostTools.find_user_name(
                            mid=mid)

            return jsonify({'peoples': peoples, 'creator': creator})

    return jsonify({}), 404
Exemplo n.º 4
0
def add(pid, task_id=None):
    ''' Add '''
    # pylint: disable=too-many-return-statements,too-many-branches
    uid = g.get('user', {}).get('account', {}).get('_id')
    if not uid:
        return jsonify({'info': 'Need login'}), 401

    is_in_project = bool(Team.participate_in(uid, pid))
    if not is_in_project:
        return jsonify({'info': 'Not in project'}), 401

    project_info = Project.get(pid=pid)
    if not project_info:
        return '404', 404

    if request.method == 'GET':
        catelist = Tasks.get_cate(pid=pid)
        return render_template('./tasks_add.html',
                               project=project_info,
                               catelist=catelist,
                               task_id=task_id)

    if request.method == 'POST':
        post_data = request.get_json()

        if post_data['casename'] == 'add':
            data = post_data['data']
            starttime = arrow.get(f"{data['date']} {data['starttime']}",
                                  tzinfo='Asia/Taipei').datetime
            endtime = None
            task_id = None

            if 'endtime' in data and data['endtime']:
                endtime = arrow.get(f"{data['date']} {data['endtime']}",
                                    tzinfo='Asia/Taipei').datetime

            if 'task_id' in post_data:
                task_id = post_data['task_id']

            send_star = False
            if 'task_id' in post_data and not post_data['task_id']:
                send_star = True

            raw = Tasks.add(pid=pid,
                            body={
                                'title': data['title'].strip(),
                                'cate': data['cate'].strip(),
                                'desc': data['desc'],
                                'limit': max((1, int(data['limit']))),
                                'starttime': starttime,
                                'created_by': uid
                            },
                            endtime=endtime,
                            task_id=task_id)

            if send_star:
                mail_tasks_star.apply_async(kwargs={
                    'pid': pid,
                    'task_id': raw['_id']
                })

            return jsonify({'data': raw})

        if post_data['casename'] == 'del':
            data = Tasks.get_with_pid(pid=pid, _id=post_data['task_id'])
            if not data:
                return jsonify({}), 404

            if data['created_by'] == g.user['account']['_id']:
                Tasks.delete(pid=pid, _id=data['_id'])

        if post_data['casename'] == 'get':
            data = Tasks.get_with_pid(pid=pid, _id=task_id)
            if not data:
                return jsonify({}), 404

            starttime = arrow.get(data['starttime']).to('Asia/Taipei')
            data['date'] = starttime.format('YYYY-MM-DD')
            data['starttime'] = starttime.format('HH:mm')

            if data['endtime']:
                endtime = arrow.get(data['endtime']).to('Asia/Taipei')
                data['endtime'] = endtime.format('HH:mm')

            data['_is_creator'] = g.user['account']['_id'] == data[
                'created_by']

            return jsonify({'data': data})

        return jsonify({})

    return jsonify({})
Exemplo n.º 5
0
def service_sync_gsuite_memberchange(sender):
    ''' Sync gsuite member change '''
    team_member_change_db = TeamMemberChangedDB()
    sync_gsuite = None
    for raw in team_member_change_db.find(
        {
            'done.gsuite_team': {
                '$exists': False
            },
            'case': {
                '$in': ('add', 'del')
            }
        },
            sort=(('create_at', 1), )):
        team = Team.get(raw['pid'], raw['tid'])

        if 'mailling' not in team or not team['mailling']:
            team_member_change_db.find_one_and_update(
                {'_id': raw['_id']}, {'$set': {
                    'done.gsuite_team': True
                }})
            continue

        if sync_gsuite is None:
            sync_gsuite = SyncGSuite(credentialfile=setting.GSUITE_JSON,
                                     with_subject=setting.GSUITE_ADMIN)

        user = User(uid=raw['uid']).get()
        if raw['case'] == 'add':
            sync_gsuite.add_users_into_group(group=team['mailling'],
                                             users=(user['mail'], ))
            team_member_change_db.find_one_and_update(
                {'_id': raw['_id']}, {'$set': {
                    'done.gsuite_team': True
                }})

        elif raw['case'] == 'del':
            sync_gsuite.del_users_from_group(group=team['mailling'],
                                             users=(user['mail'], ))
            team_member_change_db.find_one_and_update(
                {'_id': raw['_id']}, {'$set': {
                    'done.gsuite_team': True
                }})

    for raw in team_member_change_db.find(
        {
            'done.gsuite_staff': {
                '$exists': False
            },
            'case': {
                '$in': ('add', 'del')
            }
        },
            sort=(('create_at', 1), )):
        project = Project.get(raw['pid'])

        if 'mailling_staff' not in project or not project['mailling_staff']:
            team_member_change_db.find_one_and_update(
                {'_id': raw['_id']}, {'$set': {
                    'done.gsuite_staff': True
                }})
            continue

        if sync_gsuite is None:
            sync_gsuite = SyncGSuite(credentialfile=setting.GSUITE_JSON,
                                     with_subject=setting.GSUITE_ADMIN)

        user = User(uid=raw['uid']).get()
        if raw['case'] == 'add':
            sync_gsuite.add_users_into_group(group=project['mailling_staff'],
                                             users=(user['mail'], ))
            team_member_change_db.find_one_and_update(
                {'_id': raw['_id']}, {'$set': {
                    'done.gsuite_staff': True
                }})

        elif raw['case'] == 'del':
            if not Team.participate_in(uid=raw['uid'], pid=raw['pid']):
                sync_gsuite.del_users_from_group(
                    group=project['mailling_staff'], users=(user['mail'], ))

            team_member_change_db.find_one_and_update(
                {'_id': raw['_id']}, {'$set': {
                    'done.gsuite_staff': True
                }})
Exemplo n.º 6
0
def need_login():
    ''' need_login '''
    # pylint: disable=too-many-return-statements
    logging.info(
        '[X-SSL-SESSION-ID: %s] [X-REAL-IP: %s] [USER-AGENT: %s] [SESSION: %s]',
        request.headers.get('X-SSL-SESSION-ID'),
        request.headers.get('X-REAL-IP'),
        request.headers.get('USER-AGENT'),
        session,
    )

    if request.path.startswith('/user') and request.path[-1] == '/':
        return redirect(request.path[:-1])

    if 'sid' in session and session['sid']:
        mem_cahce = MC.get_client()
        user_g_data = mem_cahce.get(f"sid:{session['sid']}")

        if user_g_data:
            g.user = user_g_data  # pylint: disable=assigning-non-slot
        else:
            session_data = USession.get(session['sid'])
            if session_data:
                user_data = User(uid=session_data['uid']).get()
                if 'property' in user_data and 'suspend' in user_data['property'] and \
                        user_data['property']['suspend']:
                    session.pop('sid', None)
                    return redirect(
                        url_for('index', _scheme='https', _external=True))

                g.user = {}  # pylint: disable=assigning-non-slot
                g.user['account'] = User(uid=session_data['uid']).get()

                if g.user['account']:
                    g.user['data'] = OAuth(
                        mail=g.user['account']['mail']).get()['data']
                    g.user['participate_in'] = sorted([{
                        'pid': team['pid'],
                        'tid': team['tid'],
                        'name': team['name']
                    } for team in Team.participate_in(uid=session_data['uid'])
                                                       ],
                                                      key=lambda x: x['pid'],
                                                      reverse=True)

                    mem_cahce.set(f"sid:{session['sid']}", g.user, 600)
            else:
                session.pop('sid', None)
                session['r'] = request.path

                return redirect(
                    url_for('oauth2callback', _scheme='https', _external=True))

        return None

    if request.path in NO_NEED_LOGIN_PATH or request.path.startswith('/tasks'):
        return None

    if request.path not in NO_NEED_LOGIN_PATH:
        # ----- Let user profile public ----- #
        # if re.match(r'(\/user\/[a-z0-9]{8}).*', request.path):
        #    return

        session['r'] = request.path
        logging.info('r: %s', session['r'])
        return redirect(
            url_for('oauth2callback', _scheme='https', _external=True))

    session.pop('sid', None)
    session['r'] = request.path

    return redirect(url_for('oauth2callback', _scheme='https', _external=True))
Exemplo n.º 7
0
def need_login():
    app.logger.info(
        '[X-SSL-SESSION-ID: %s] [X-REAL-IP: %s] [USER-AGENT: %s] [SESSION: %s]'
        % (
            request.headers.get('X-SSL-SESSION-ID'),
            request.headers.get('X-REAL-IP'),
            request.headers.get('USER-AGENT'),
            session,
        ))

    if request.path.startswith('/user') and request.path[-1] == '/':
        return redirect(request.path[:-1])

    if 'sid' in session and session['sid']:
        mc = MC.get_client()
        user_g_data = mc.get('sid:%s' % session['sid'])

        if user_g_data:
            g.user = user_g_data
        else:
            session_data = USession.get(session['sid'])
            if session_data:
                user_data = User(uid=session_data['uid']).get()
                if 'property' in user_data and 'suspend' in user_data[
                        'property'] and user_data['property']['suspend']:
                    session.pop('sid', None)
                    return redirect(
                        url_for('index', _scheme='https', _external=True))

                g.user = {}
                g.user['account'] = User(uid=session_data['uid']).get()

                if g.user['account']:
                    g.user['data'] = OAuth(
                        mail=g.user['account']['mail']).get()['data']
                    g.user['participate_in'] = sorted([{
                        'pid': team['pid'],
                        'tid': team['tid'],
                        'name': team['name']
                    } for team in Team.participate_in(uid=session_data['uid'])
                                                       ],
                                                      key=lambda x: x['pid'],
                                                      reverse=True)

                    mc.set('sid:%s' % session['sid'], g.user, 600)
                else:
                    session.pop('sid', None)
                    session['r'] = request.path
                    return redirect(
                        url_for('oauth2callback',
                                _scheme='https',
                                _external=True))
            else:
                session.pop('sid', None)
                session['r'] = request.path
                return redirect(
                    url_for('oauth2callback', _scheme='https', _external=True))

    else:
        if request.path.startswith('/tasks'):
            return

        if request.path not in NO_NEED_LOGIN_PATH:
            # ----- Let user profile public ----- #
            #if re.match(r'(\/user\/[a-z0-9]{8}).*', request.path):
            #    return

            session['r'] = request.path
            app.logger.info('r: %s' % session['r'])
            return redirect(
                url_for('oauth2callback', _scheme='https', _external=True))