Add authorize page

This commit is contained in:
Mootfrost 2025-04-15 22:01:12 +03:00
parent 24b988b484
commit 239ccc1615
3 changed files with 164 additions and 9 deletions

View file

@ -47,13 +47,9 @@ async def get_user(user_id):
def get_spotify_link(user_id) -> str:
params = {
'client_id': config.spotify.client_id,
'response_type': 'code',
'redirect_uri': config.spotify.redirect,
'scope': 'user-read-recently-played user-read-currently-playing',
'state': user_id
}
return f"https://accounts.spotify.com/authorize?{urllib.parse.urlencode(params)}"
return f"https://music.mootfrost.dev/spotify/authorize?{urllib.parse.urlencode(params)}"
def get_ymusic_link(user_id) -> str:
@ -69,7 +65,7 @@ def get_ymusic_link(user_id) -> str:
async def start(e: events.NewMessage.Event):
payload = {
'tg_id': e.chat_id,
'exp': int(time.time()) + 300
'exp': int(time.time()) + 900
}
enc_user_id = jwt.encode(payload, config.jwt_secret, algorithm='HS256')
buttons = [

View file

@ -1,3 +1,4 @@
import urllib.parse
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession
@ -6,7 +7,7 @@ from fastapi.staticfiles import StaticFiles
import uvicorn
from telethon import TelegramClient
import aiohttp
import time
from pydantic import BaseModel
import jwt
from app.dependencies import get_session
@ -69,7 +70,44 @@ You can change default service using /default command.
"""
@app.get('/spotify_callback')
def get_spotify_link(client_id, state) -> str:
params = {
'client_id': client_id,
'response_type': 'code',
'redirect_uri': config.spotify.redirect,
'scope': 'user-read-recently-played user-read-currently-playing',
'state': state
}
return f"https://accounts.spotify.com/authorize?{urllib.parse.urlencode(params)}"
class SpotifyAuthorizeRequest(BaseModel):
client_id: str
client_secret: str
state: str
@app.post('/spotify/authorize')
async def spotify_authorize(data: SpotifyAuthorizeRequest, session: AsyncSession = Depends(get_session)):
user_id = get_decoded_id(data.state)
creds = {
'client_id': data.client_id,
'client_secret': data.client_secret
}
user = await session.get(User, user_id)
if user:
user.spotify_auth = creds
else:
user = User(id=user_id,
spotify_auth=creds,
default='spotify'
)
session.add(user)
await session.commit()
return {'redirect_url': get_spotify_link(data.client_id, client.state)}
@app.get('/spotify/callback')
async def spotify_callback(code: str, state: str, session: AsyncSession = Depends(get_session)):
user_id = get_decoded_id(state)
token, refresh_token, expires_in = await code_to_token(code, 'https://accounts.spotify.com/api/token', config.spotify)
@ -93,7 +131,7 @@ async def spotify_callback(code: str, state: str, session: AsyncSession = Depend
@app.get('/ym_callback')
@app.get('/ym/callback')
async def ym_callback(state: str, code: str, cid: str, session: AsyncSession = Depends(get_session)):
user_id = get_decoded_id(state)
token, refresh_token, expires_in = await code_to_token(code, 'https://oauth.yandex.com/token', config.ymusic, config.proxy)

View file

@ -0,0 +1,121 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Spotify API Authorization</title>
<style>
body {
margin: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #e5e7eb;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
flex-direction: column;
padding: 20px;
}
h1 {
font-size: 1.5rem;
color: #1f2937;
margin-bottom: 1rem;
text-align: center;
}
ol {
padding-left: 1.25rem;
margin-bottom: 1.5rem;
color: #4b5563;
font-size: 0.95rem;
max-width: 400px;
}
label {
display: block;
font-weight: 600;
margin-bottom: 0.25rem;
color: #374151;
font-size: 0.95rem;
}
input {
width: 100%;
max-width: 400px;
padding: 0.6rem;
margin-bottom: 1rem;
border: 1px solid #d1d5db;
border-radius: 0.5rem;
font-size: 1rem;
background-color: white;
}
button {
background-color: #22c55e;
color: white;
border: none;
padding: 0.75rem;
font-size: 1rem;
border-radius: 0.5rem;
width: 100%;
max-width: 400px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #16a34a;
}
</style>
</head>
<body>
<h1>Spotify API Setup</h1>
<ol>
<li>Visit <a href="https://developer.spotify.com/dashboard" target="_blank">Spotify Developer Dashboard</a></li>
<li>Log in and create an app</li>
<li>Fill any name and description. Set redirect url to: {{}}</li>
<li>Copy your <strong>Client ID</strong> and <strong>Client Secret</strong></li>
</ol>
<label for="clientId">Client ID</label>
<input type="text" id="clientId" placeholder="Enter your Client ID" />
<label for="clientSecret">Client Secret</label>
<input type="password" id="clientSecret" placeholder="Enter your Client Secret" />
<input type="hidden" id="state" value="{{ Pin }}">
<button id="authorizeBtn" onclick="">Authorize</button>
<script>
document.getElementById('authorizeBtn').addEventListener('click', async () => {
const clientId = document.getElementById('clientId').value;
const clientSecret = document.getElementById('clientSecret').value;
try {
const response = await fetch(window.location.origin + '/spotify/authorize', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ client_id: clientId, client_secret: clientSecret, state: document.querySelector('#state').value }),
});
if (!response.ok) {
throw new Error('Authorization failed');
}
const data = await response.json();
if (data.redirect_url) {
window.location.href = data.redirect_url;
} else {
alert('No redirect URL returned');
}
} catch (error) {
console.error('Error:', error);
alert('Something went wrong during authorization.');
}
});
</script>
</body>
</html>