Example #1
0
async def oauth_login(request):
    google_client = GoogleClient(
        client_id=request.app.config.GOOGLE_ID,
        client_secret=request.app.config.GOOGLE_SECRET,
    )

    redirect_url = request.url.origin().join(
        request.app.router["oauth:login"].url_for())

    logger.debug("Start OAUTH2")
    if not request.url.query.get("code"):
        logger.debug("Code isn't exist")
        return web.HTTPFound(
            google_client.get_authorize_url(
                redirect_uri=redirect_url,
                scope="email profile",
            ))

    logger.debug("Code {} was received successfully".format(
        request.url.query["code"]))

    token, data = await google_client.get_access_token(
        request.url.query["code"],
        redirect_uri=redirect_url,
    )

    logger.debug("Token {} was received successfully".format(token))

    session = await get_session(request)
    session['token'] = token

    logger.debug("Redirect URL: {}".format(redirect_url))

    return web.HTTPFound(request.app.router["oauth:complete"].url_for())
Example #2
0
 async def get_oauth_url(self, request, session, state):
     gc = GoogleClient(client_id=self._id, client_secret=self._secret)
     authorize_url = gc.get_authorize_url(
         scope=
         'email profile https://www.googleapis.com/auth/admin.directory.user.readonly',
         redirect_uri=self.redirect_uri,
         state=state)
     return authorize_url
Example #3
0
 async def get_oauth_url(self, request, session, state):
     gc = GoogleClient(
         client_id=self._id,
         client_secret=self._secret
     )
     authorize_url = gc.get_authorize_url(
         scope='openid email profile',
         redirect_uri=self.redirect_uri,
         state=state,
         hd=self.org)
     return authorize_url
async def oauth(request):
    client = GoogleClient(client_id=cfg.client_id,
                          client_secret=cfg.client_secret)

    if 'code' not in request.GET:
        return web.HTTPFound(
            client.get_authorize_url(scope='email profile',
                                     redirect_uri=cfg.redirect_uri))
    token, data = await client.get_access_token(request.GET['code'],
                                                redirect_uri=cfg.redirect_uri)
    session = await get_session(request)
    session['token'] = token
    return web.HTTPFound('/')
Example #5
0
async def oauth(request):
    client = GoogleClient(client_id=cfg.client_id,
                          client_secret=cfg.client_secret)

    if 'code' not in request.url.query:
        return ResponseRedirect(
            client.get_authorize_url(scope='email profile',
                                     redirect_uri=cfg.redirect_uri))

    token, data = await client.get_access_token(request.url.query['code'],
                                                redirect_uri=cfg.redirect_uri)
    request.session['token'] = token
    return ResponseRedirect('/')
Example #6
0
async def oauth_login(request):
    client = GoogleClient(client_id=request.app.config.OAUTH_ID,
                          client_secret=request.app.config.OAUTH_SECRET)
    if 'code' not in request.GET:
        return web.HTTPFound(
            client.get_authorize_url(
                redirect_uri=request.app.config.REDIRECT_URI,
                scope='email profile'))
    token, data = await client.get_access_token(
        request.GET['code'], redirect_uri=request.app.config.REDIRECT_URI)
    session = await get_session(request)
    session['token'] = token

    return web.HTTPFound(request.app.router['oauth:complete'].url_for())
async def oauth(request):
    client = GoogleClient(
        client_id=cfg.client_id,
        client_secret=cfg.client_secret
    )

    if 'code' not in request.GET:
        return web.HTTPFound(client.get_authorize_url(
            scope='email profile',
            redirect_uri=cfg.redirect_uri
        ))
    token, data = await client.get_access_token(
        request.GET['code'],
        redirect_uri=cfg.redirect_uri
    )
    session = await get_session(request)
    session['token'] = token
    return web.HTTPFound('/')
Example #8
0
def google(request):
    google = GoogleClient(
        client_id='150775235058-9fmas709maee5nn053knv1heov12sh4n.apps.googleusercontent.com',
        client_secret='df3JwpfRf8RIBz-9avNW8Gx7',

        redirect_uri='http://%s%s' % (request.host, request.path),
        scope='email profile',
    )
    if 'code' not in request.GET:
        return web.HTTPFound(google.get_authorize_url())

    # Get access token
    code = request.GET['code']
    token = yield from google.get_access_token(code)

    # Get a resource
    response = yield from google.request('GET', 'people/me')
    body = yield from response.read()
    return web.Response(body=body, content_type='application/json')
Example #9
0
class ImageSaverCog(commands.Cog, name="Image saver cog"):
    def __init__(
        self,
        bot,
        client_id,
        client_secret,
        aiohttp_address,
        callback_address,
        port,
        loop=None,
        users=None,
        watching=None,
    ):
        self.loop = loop if loop else asyncio.get_event_loop()
        self.bot = bot
        self.google = GoogleClient(
            client_id=client_id, client_secret=client_secret, redirect_uri=f'http://{callback_address}:{port}/callback'
        )
        self.users = (
            self.load_users(users, self.google, loop=self.loop) if users else {}
        )
        self.watching = self.load_watching(watching) if watching else {}
        self.upload_queue = asyncio.Queue()
        app = web.Application()
        app.add_routes([web.get("/callback", self.callback)])
        self.upload.start()
        self.runner = web.AppRunner(app)
        self.loop.run_until_complete(self.runner.setup())
        site = web.TCPSite(self.runner, aiohttp_address, 8080)
        self.web_task = asyncio.Task(site.start(), loop=loop)
        self.loggingOn = False

    @staticmethod
    def load_users(json, auth_client, loop=None):
        loop = loop if loop else asyncio.get_event_loop()
        return {
            int(user): Token.load(token, auth_client, loop)
            for user, token in json.items()
        }

    @staticmethod
    def load_watching(json):
        return {
            int(channel): {
                int(author_id): user_id for author_id, user_id in users.items()
            }
            for channel, users in json.items()
        }

    def cog_unload(self):
        self.upload.cancel()
        self.loop.run_until_complete(self._stop())

    async def _stop(self):
        await self.runner.cleanup()
        await self.web_task
        self.save()

    def save(self):
        users = {u: t.save() for u, t in self.users.items()}
        with open("users.json", "w") as f:
            json.dump(users, f)
        with open("watching.json", "w") as f:
            json.dump(self.watching, f)

    @tasks.loop()
    async def upload(self):
        u = await self.upload_queue.get()
        upload_tokens = []
        async with aiohttp.ClientSession(
            headers={"Authorization": f"Bearer {str(u.bearer)}"}
        ) as session:
            for pic in u.pictures:
                async with session.post(
                    "https://photoslibrary.googleapis.com/v1/uploads",
                    data=await pic.attachment.read(),
                    headers={
                        "Content-Type": "application/octect-stream",
                        "X-Goog-Upload-File-Name": pic.attachment.filename,
                        "X-Goog-Upload-Protocol": "raw",
                    },
                ) as resp:
                    await u.update1(resp)
                    if resp.status == 200:
                        upload_tokens.append(
                            {"description": pic.description, "token": await resp.text()}
                        )
            if len(upload_tokens) > 0:
                async with session.post(
                    "https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate",
                    json={
                        "newMediaItems": [
                            {
                                "description": t["description"],
                                "simpleMediaItem": {"uploadToken": t["token"]},
                            }
                            for t in upload_tokens
                        ]
                    },
                ) as resp:
                    await u.update2(resp)

    @commands.Command
    async def login(self, ctx):
        id = ctx.author.id
        authorize_url = self.google.get_authorize_url(
            scope="https://www.googleapis.com/auth/photoslibrary.appendonly",
            state=str(id),
            access_type="offline",
        )
        await ctx.author.send(f"Login with google here: {authorize_url}")

    @commands.Command
    async def watch(self, ctx, user: commands.UserConverter):
        channel_id = int(ctx.channel.id)
        user_id = int(user.id)
        author_id = int(ctx.author.id)
        if not self.watching.get(channel_id):
            self.watching[channel_id] = {}
        if not self.watching.get(channel_id).get(user_id):
            self.watching[channel_id][user_id] = []
        if not author_id in self.watching.get(channel_id).get(user_id):
            self.watching[channel_id][user_id].append(author_id)
        await ctx.send(
            f"I'm watching {user} for images in this channel to upload to {ctx.author}'s google photos library'"
        )

    @commands.Cog.listener()
    async def on_message(self, message):
        # are we watching this channel?
        if message.author != self.bot.user:
            channel = self.watching.get(message.channel.id)
            if channel:
                # are we watching any users in this channel?
                users = channel.get(message.author.id, [])
                # upload for all users we're watching for.
                for user_id in users:
                    if user_id in self.users.keys():
                        # Message has title + 1 picture
                        if message.content and len(message.attachments) == 1:
                            upload = Upload(
                                self.bot,
                                [Picture(message.content, message.attachments[0])],
                                message,
                                self.users[user_id],
                                self.bot.get_user(user_id),
                                self.loggingOn,
                            )
                            await self.upload_queue.put(upload)
                            await upload.log()
                        elif len(message.attachments) > 0:
                            upload = Upload(
                                self.bot,
                                [Picture(a.filename, a) for a in message.attachments],
                                message,
                                self.users[user_id],
                                self.bot.get_user(user_id),
                                self.loggingOn,
                            )
                            await self.upload_queue.put(upload)
                            await upload.log()

    @commands.command()
    @commands.is_owner()
    async def stop(self, ctx):
        await self.bot.logout()

    @commands.command()
    @commands.is_owner()
    async def check(self, ctx):
        await ctx.author.send(f"users: {self.users}")
        await ctx.author.send(f"watching: {self.watching}")

    @commands.group()
    @commands.is_owner()
    async def logging(self, ctx):
        if ctx.invoked_subcommand is None:
            await ctx.author.send("Invalid logging command")

    @logging.command()
    async def on(self, ctx):
        self.loggingOn = True
        await ctx.author.send("Logging turned on")

    @logging.command()
    async def off(self, ctx):
        self.loggingOn = False
        await ctx.author.send("Logging turned off")

    async def callback(self, request):
        user_id = request.query.get("state")
        code = request.query.get("code")
        otoken, meta = await self.google.get_access_token(code)
        self.users[int(user_id)] = Token(
            otoken,
            meta.get("refresh_token"),
            meta.get("expires_in"),
            self.google,
            loop=self.loop,
        )
        return web.Response(
            text="Thank you, you can now close this tab and go back to discord"
        )
Example #10
0
from aiohttp import web

import jwt
from aioauth_client import GoogleClient

from conf import APP_SECRET, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
from authorization.utils import experied_at
from authorization.models import RefreshToken
from models import User

google_client = GoogleClient(
    client_id=GOOGLE_CLIENT_ID,
    client_secret=GOOGLE_CLIENT_SECRET,
    redirect_uri='http://localhost:5000/auth/google/sucess')
scope = 'https://www.googleapis.com/auth/userinfo.email'
google_authorize_url = google_client.get_authorize_url(scope=scope)


async def google_auth(request):
    raise web.HTTPFound(google_authorize_url)


async def google_auth_sucess(request):
    code = request.rel_url.query.get('code')

    if not code:
        return web.HTTPBadRequest()

    access_token, _ = await google_client.get_access_token(code)

    google = GoogleClient(