Skip to content

Instantly share code, notes, and snippets.

@gotwarlost
Created July 14, 2024 02:58
Show Gist options
  • Save gotwarlost/19504812224e19b6044eb47ae91dd493 to your computer and use it in GitHub Desktop.
Save gotwarlost/19504812224e19b6044eb47ae91dd493 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
const API_URL = 'http://your-api-url.com';
const LoginScreen = ({ navigation }) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async () => {
try {
const response = await axios.post(`${API_URL}/token`, {
username,
password,
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const { access_token } = response.data;
await AsyncStorage.setItem('userToken', access_token);
// Navigate to the main app screen
navigation.navigate('Home');
} catch (error) {
Alert.alert('Login Failed', 'Please check your credentials and try again.');
}
};
return (
<View>
<TextInput
placeholder="Username"
value={username}
onChangeText={setUsername}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button title="Login" onPress={handleLogin} />
</View>
);
};
export default LoginScreen;
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from datetime import datetime, timedelta
app = FastAPI()
# Secret key and algorithm for JWT
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# OAuth2 scheme
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# User model
class User(BaseModel):
username: str
email: str | None = None
full_name: str | None = None
disabled: bool | None = None
# Token model
class Token(BaseModel):
access_token: str
token_type: str
# Function to verify password
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
# Function to get password hash
def get_password_hash(password):
return pwd_context.hash(password)
# Function to authenticate user (replace with your actual user authentication logic)
def authenticate_user(username: str, password: str):
# Here you would typically query your database
# For this example, we'll use a hardcoded user
if username != "testuser":
return False
hashed_password = get_password_hash("testpassword")
if not verify_password(password, hashed_password):
return False
return User(username=username, email="test@example.com")
# Function to create access token
def create_access_token(data: dict, expires_delta: timedelta | None = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
# Login endpoint
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
# Protected route example
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(oauth2_scheme)):
return current_user
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
const API_URL = 'http://your-api-url.com';
const getAuthenticatedUserData = async () => {
try {
const token = await AsyncStorage.getItem('userToken');
const response = await axios.get(`${API_URL}/users/me`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
return response.data;
} catch (error) {
console.error('Error fetching user data:', error);
// Handle error (e.g., redirect to login if token is invalid)
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment