Introduction to ghauth
ghauth
is a powerful authentication library designed to easily integrate GitHub’s authentication into your application. It provides a range of APIs that streamline the process of obtaining access tokens and interacting with the GitHub API.
Getting Started
To start using ghauth
, you need to install it via npm:
npm install ghauth
Example: Authenticate GitHub Users
Here’s a basic example of how to authenticate GitHub users using ghauth
:
const ghauth = require('ghauth');
(async () => {
const authOptions = {
scopes: ['user'],
note: 'example-app'
};
try {
const authData = await ghauth(authOptions);
console.log('Token:', authData.token);
} catch (error) {
console.error('Error authenticating:', error);
}
})();
API Examples
Using the Authentication Token
Once authenticated, you can use the token to make authorized requests to the GitHub API:
const axios = require('axios');
const token = 'YOUR_ACCESS_TOKEN';
axios.get('https://api.github.com/user', {
headers: {
Authorization: `token ${token}`
}
})
.then(response => {
console.log('User Data:', response.data);
}).catch(error => {
console.error('Error fetching user data:', error);
});
Creating a GitHub Repository
You can also create a new repository using the authenticated token:
axios.post('https://api.github.com/user/repos', {
name: 'new-repo'
}, {
headers: {
Authorization: `token ${token}`
}
})
.then(response => {
console.log('Repository Created:', response.data);
}).catch(error => {
console.error('Error creating repository:', error);
});
Listing User Repositories
Here is how to list repositories for an authenticated user:
axios.get('https://api.github.com/user/repos', {
headers: {
Authorization: `token ${token}`
}
})
.then(response => {
console.log('Repositories:', response.data);
}).catch(error => {
console.error('Error listing repositories:', error);
});
Building an App with ghauth
An example app that uses the above APIs can be structured as follows:
const express = require('express');
const ghauth = require('ghauth');
const axios = require('axios');
const app = express();
const PORT = 3000;
app.get('/auth', async (req, res) => {
try {
const authData = await ghauth({
scopes: ['user', 'repo'],
note: 'example-app'
});
res.json(authData);
} catch (error) {
res.status(500).send('Error during authentication');
}
});
app.get('/user', async (req, res) => {
const token = req.query.token;
if (!token) {
return res.status(400).send('Token required');
}
try {
const response = await axios.get('https://api.github.com/user', {
headers: {
Authorization: `token ${token}`
}
});
res.json(response.data);
} catch (error) {
res.status(500).send('Error fetching user data');
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Using the above application, you can easily integrate GitHub authentication and APIs to manage user data, repositories, and other GitHub resources seamlessly.
Hash: 2e368fcc430c5f3aa60c7f8761c2837cd48f1263288bb24a15152e5081cd6f06