Exemplo n.º 1
0
def mail_member_welcome(sender, **kwargs):
    TPLENV = Environment(loader=FileSystemLoader('./templates/mail'))
    template = TPLENV.get_template('./welcome.html')

    awsses = AWSSES(aws_access_key_id=setting.AWS_ID,
                    aws_secret_access_key=setting.AWS_KEY,
                    source=setting.AWS_SES_FROM)

    uids = []
    for u in MailLetterDB().need_to_send(code='welcome'):
        uids.append(u['_id'])

    if not uids:
        return

    service_sync_mattermost_invite.apply_async(kwargs={'uids': uids})
    users = User.get_info(uids=uids)

    for uid in uids:
        logger.info('uid: %s' % uid)
        body = template.render(name=users[uid]['profile']['badge_name'], )

        raw_mail = awsses.raw_mail(
            to_addresses=(dict(name=users[uid]['profile']['badge_name'],
                               mail=users[uid]['oauth']['email']), ),
            subject=u'歡迎使用志工服務系統 - %s' % users[uid]['profile']['badge_name'],
            body=body,
        )

        resp = awsses.send_raw_email(data=raw_mail)
        logger.info(resp)
        if resp['ResponseMetadata']['HTTPStatusCode'] != 200:
            raise Exception('HTTPStatusCode not `200`, do retry')

        MailLetterDB().make_sent(uid=uid, code='welcome')
Exemplo n.º 2
0
def make_index() -> None:
    ''' Make index for the collection with `index()` '''
    BudgetDB().index()
    ExpenseDB().index()
    FormDB().index()
    MailLetterDB().index()
    MattermostLinkDB().index()
    MattermostUsersDB().index()
    OAuthDB().index()
    ProjectDB(pid='').index()
    SenderReceiverDB().index()
    TeamDB(pid='', tid='').index()
    TeamMemberChangedDB().index()
    TeamMemberTagsDB().index()
    TeamPlanDB().index()
    TelegramDB().index()
    USessionDB().index()
    UsersDB().index()
    WaitListDB().index()
Exemplo n.º 3
0
from models.formdb import FormDB
from models.mailletterdb import MailLetterDB
from models.mattermost_link_db import MattermostLinkDB
from models.mattermostdb import MattermostUsersDB
from models.oauth_db import OAuthDB
from models.projectdb import ProjectDB
from models.senderdb import SenderReceiverDB
from models.teamdb import TeamDB
from models.teamdb import TeamMemberChangedDB
from models.teamdb import TeamMemberTagsDB
from models.teamdb import TeamPlanDB
from models.users_db import UsersDB
from models.usessiondb import USessionDB
from models.waitlistdb import WaitListDB

if __name__ == '__main__':
    FormDB().index()
    MailLetterDB().index()
    MattermostLinkDB().index()
    MattermostUsersDB().index()
    OAuthDB().index()
    ProjectDB(pid=None).index()
    SenderReceiverDB().index()
    TeamDB(pid=None, tid=None).index()
    TeamMemberChangedDB().index()
    TeamMemberTagsDB().index()
    TeamPlanDB().index()
    USessionDB().index()
    UsersDB().index()
    WaitListDB().index()
Exemplo n.º 4
0
def oauth2callback():
    ''' oauth2callback '''
    if 'r' in request.args and request.args['r'].startswith('/'):
        session['r'] = request.args['r']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        './client_secret.json',
        scopes=(
            'openid',
            'https://www.googleapis.com/auth/userinfo.email',
            'https://www.googleapis.com/auth/userinfo.profile',
        ),
        redirect_uri=f'https://{setting.DOMAIN}/oauth2callback',
    )

    if 'code' not in request.args:
        authorization_url, state = flow.authorization_url(
            access_type='offline',
            include_granted_scopes='true',
            state=hashlib.sha256(os.urandom(2048)).hexdigest(),
        )

        session['state'] = state
        return redirect(authorization_url)

    url = request.url.replace('http://', 'https://')
    url_query = parse_qs(urlparse(url).query)

    if 'state' in url_query and url_query['state'] and \
            url_query['state'][0] == session.get('state'):
        flow.fetch_token(authorization_response=url)

        auth_client = discovery.build('oauth2',
                                      'v2',
                                      credentials=flow.credentials,
                                      cache_discovery=False)
        user_info = auth_client.userinfo().get().execute()

        # ----- save oauth info ----- #
        OAuth.add(mail=user_info['email'],
                  data=user_info,
                  token=flow.credentials)

        # ----- Check account or create ----- #
        owner = OAuth.owner(mail=user_info['email'])
        if owner:
            user = User(uid=owner).get()
        else:
            user = User.create(mail=user_info['email'])
            MailLetterDB().create(uid=user['_id'])

        user_session = USession.make_new(uid=user['_id'],
                                         header=dict(request.headers))
        session['sid'] = user_session.inserted_id

        if 'r' in session:
            redirect_path = session['r']
            logging.info('login r: %s', redirect_path)
            session.pop('r', None)
            session.pop('state', None)
            return redirect(redirect_path)

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

    session.pop('state', None)
    return redirect(url_for('oauth2callback', _scheme='https', _external=True))