Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitgnore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/osdg-web/.env.local
178 changes: 178 additions & 0 deletions CAS_AUTHENTICATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
# CAS Authentication Setup Guide

This guide explains how to set up and use the CAS (Central Authentication Service) authentication system integrated into the OSDG website.

## Overview

The CAS authentication system allows users to log in using their IIIT Hyderabad credentials. It's based on the authentication flow from the Discord-CAS project but adapted for web use.

## Files Structure

```
src/
├── app/
│ ├── api/auth/
│ │ ├── cas/
│ │ │ ├── login/route.ts # Initiates CAS login
│ │ │ └── callback/route.ts # Handles CAS callback
│ │ ├── user/route.ts # Get current user info
│ │ └── logout/route.ts # Logout endpoint
│ └── login/page.tsx # Login page UI
├── components/
│ ├── AuthWidget.tsx # Combined login/profile widget
│ ├── LoginButton.tsx # Login button component
│ └── UserProfile.tsx # User profile display
└── contexts/
└── AuthContext.tsx # Authentication state management
```

## Environment Variables

Create a `.env.local` file in the root directory with:

```bash
# CAS Server Configuration
CAS_BASE_URL=https://cas.iiit.ac.in

# Next.js Site Configuration
NEXTAUTH_URL=http://localhost:3000

# JWT Secret (generate a secure random string)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# Environment
NODE_ENV=development
```

## How It Works

### 1. Authentication Flow

1. User clicks "Login with IIIT CAS" button
2. System redirects to `/api/auth/cas/login`
3. API redirects to CAS server with service URL
4. User authenticates on CAS server
5. CAS redirects back to `/api/auth/cas/callback` with ticket
6. System validates ticket with CAS server
7. If valid, creates JWT session and sets secure cookie
8. User is redirected to the intended page

### 2. User Data

The system extracts the following data from CAS:
- `username`: IIIT username
- `name`: Full name
- `email`: Email address
- `rollno`: Roll number (if available)

### 3. Session Management

- Sessions are stored as JWT tokens in secure HTTP-only cookies
- Tokens expire after 24 hours
- Users can logout, which clears the session and redirects to CAS logout

## Usage

### Using the Authentication Context

```tsx
import { useAuth } from '@/contexts/AuthContext';

function MyComponent() {
const { user, loading, login, logout } = useAuth();

if (loading) return <div>Loading...</div>;

if (user) {
return (
<div>
<p>Welcome, {user.name}!</p>
<button onClick={logout}>Logout</button>
</div>
);
}

return <button onClick={() => login()}>Login</button>;
}
```

### Using Components

```tsx
import AuthWidget from '@/components/AuthWidget';
import LoginButton from '@/components/LoginButton';

// Complete authentication widget (shows login button or user profile)
<AuthWidget />

// Just the login button
<LoginButton returnTo="/dashboard" />
```

## API Endpoints

- `GET /api/auth/cas/login?returnTo=/path` - Initiate CAS login
- `GET /api/auth/cas/callback` - Handle CAS callback (internal)
- `GET /api/auth/user` - Get current user information
- `POST /api/auth/logout` - Logout user

## Security Features

- JWT tokens with secure signing
- HTTP-only cookies (cannot be accessed by JavaScript)
- Secure cookies in production
- CSRF protection through SameSite cookie attribute
- Token expiration (24 hours)
- Proper CAS ticket validation

## Development

1. Install dependencies:
```bash
npm install jose
```

2. Set up environment variables in `.env.local`

3. Start development server:
```bash
npm run dev
```

4. Test login at: http://localhost:3000/login

## Production Deployment

1. Update `NEXTAUTH_URL` to your production domain
2. Generate a secure `JWT_SECRET`
3. Ensure `NODE_ENV=production`
4. Configure your web server to handle the authentication routes

## Troubleshooting

### Common Issues

1. **CAS validation fails**: Check that `CAS_BASE_URL` is correct
2. **JWT errors**: Ensure `JWT_SECRET` is set and consistent
3. **Redirect loops**: Verify `NEXTAUTH_URL` matches your domain
4. **Cookie issues**: Check secure/sameSite settings in production

### Debug Mode

Enable debug logging by adding console.log statements in the callback route to see CAS responses.

## Integration with Discord-CAS

This implementation is compatible with the Discord-CAS project structure:
- Uses the same CAS server endpoint
- Extracts the same user attributes
- Follows similar authentication patterns
- Can be extended to integrate with Discord bot features

## Future Enhancements

- Database storage for persistent sessions
- Role-based access control
- Integration with Discord server verification
- Admin panel for user management
- Audit logging for security
122 changes: 122 additions & 0 deletions CAS_AUTHENTICATION_UPDATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# CAS Authentication Update

## Summary
Updated CAS authentication implementation based on the working forms-portal project to use IIIT's official CAS server at `https://login.iiit.ac.in/cas`.

## Changes Made

### 1. Updated CAS Base URL
- **Old**: `https://cas.iiit.ac.in` (incorrect)
- **New**: `https://login.iiit.ac.in/cas` (correct IIIT CAS endpoint)

### 2. Login Route (`src/app/api/auth/cas/login/route.ts`)
- Updated CAS_BASE_URL to use `login.iiit.ac.in/cas`
- Changed NEXTAUTH_URL to NEXT_PUBLIC_SITE_URL for consistency
- Improved service URL construction to include returnTo parameter

### 3. Callback Route (`src/app/api/auth/cas/callback/route.ts`)
**Major improvements based on forms-portal:**
- **JSON Format**: Added `&format=JSON` to CAS serviceValidate request instead of parsing XML
- **Response Structure**: Updated to handle IIIT CAS JSON response format:
```typescript
{
serviceResponse: {
authenticationSuccess: {
attributes: {
uid: string[],
Name: string[],
'E-Mail': string[]
}
}
}
}
```
- **Better Error Handling**: Check for authenticationFailure in response
- **Service URL Matching**: Service URL in validation matches the one sent to login
- **Removed XML Parsing**: No more regex parsing of XML responses

### 4. Logout Route (`src/app/api/auth/cas/logout/route.ts`)
- Updated CAS_BASE_URL
- Added GET method for direct logout redirect
- Simplified logout URL (removed unnecessary parameters)

### 5. Environment Variables (`.env.local`)
Added CAS configuration:
```bash
CAS_BASE_URL=https://login.iiit.ac.in/cas
JWT_SECRET=your-secret-key-change-this-in-production
```

### 6. Markdown Support (`src/components/ChatModal.tsx`)
- Fixed TypeScript errors by wrapping ReactMarkdown in div with className
- Added prose styling for proper markdown rendering:
- Code blocks with syntax highlighting
- Lists with proper spacing
- Inline code with green highlighting
- Responsive typography

## Key Improvements

### From XML to JSON
**Before:**
```typescript
const xmlText = await response.text();
const usernameMatch = xmlText.match(/<cas:user>([^<]+)<\/cas:user>/);
```

**After:**
```typescript
const data: CASResponse = await response.json();
const username = data.serviceResponse.authenticationSuccess?.attributes.uid[0];
```

### Proper Attribute Extraction
IIIT CAS returns attributes in a specific format:
- `uid[]` - Username/Roll number
- `Name[]` - Full name
- `E-Mail[]` - Email address

All arrays with first element containing the actual value.

### Service URL Consistency
The service URL sent to `/login` must exactly match the one used in `/serviceValidate`:
```typescript
// Login
const serviceUrl = `${SITE_URL}/api/auth/cas/callback?returnTo=${encodeURIComponent(returnTo)}`;

// Callback validation
const serviceUrl = `${SITE_URL}/api/auth/cas/callback?returnTo=${encodeURIComponent(returnTo)}`;
```

## Testing Checklist

- [ ] Login redirects to `https://login.iiit.ac.in/cas/login`
- [ ] After IIIT credentials, redirects back to callback
- [ ] Callback receives ticket parameter
- [ ] Ticket validation returns user data (uid, Name, E-Mail)
- [ ] JWT token created and stored in cas-auth cookie
- [ ] User redirected to returnTo path or home
- [ ] `/api/auth/user` returns user info from JWT
- [ ] Logout clears cookie and redirects to CAS logout

## Production Considerations

1. **JWT Secret**: Change `JWT_SECRET` to a strong random value in production
2. **HTTPS**: Ensure `secure: true` for cookies in production
3. **CORS**: Configure appropriate CORS headers if frontend is on different domain
4. **Rate Limiting**: Add rate limiting to prevent abuse of auth endpoints
5. **Logging**: Monitor CAS validation failures for debugging

## Differences from forms-portal

The forms-portal uses Go backend with Echo framework, while osdg-web uses Next.js:
- **Session Management**: Forms-portal uses custom session system, we use JWT
- **Database**: Forms-portal stores users in PostgreSQL, we keep auth stateless
- **Response Format**: Both now use JSON format with `&format=JSON` parameter
- **Error Handling**: Similar approach with proper error codes and redirects

## References

- IIIT CAS Endpoint: https://login.iiit.ac.in/cas
- Forms Portal: `meow/forms-portal/server/handlers/auth/main.go`
- CAS Protocol: https://apereo.github.io/cas/6.6.x/protocol/CAS-Protocol-Specification.html
Loading