Skip to content
Snippets Groups Projects
Commit 7f967c34 authored by Guillaume Vagner's avatar Guillaume Vagner
Browse files

je sais pas utiliser git

parents 8505f560 06828985
Branches debuging
No related tags found
No related merge requests found
<!DOCTYPE html>
<html>
<title>Happy Botday !</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<style>
body,
h1 {
font-family: "Raleway", sans-serif
}
body,
html {
height: 100%
}
.bgimg {
background-image: url('/background.jpg');
min-height: 100%;
background-position: center;
background-size: cover;
}
</style>
<body>
<div class="bgimg w3-display-container w3-animate-opacity w3-text-white">
<div class="w3-display-middle">
<p class="w3-large w3-center">Connecté ! Tu peux fermer cette fenêtre.
</p>
</div>
</div>
</body>
</html>
\ No newline at end of file
background.jpg

163 KiB

<!DOCTYPE html>
<html>
<title>Happy Botday !</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<style>
body,
h1 {
font-family: "Raleway", sans-serif
}
body,
html {
height: 100%
}
.bgimg {
background-image: url('/background.jpg');
min-height: 100%;
background-position: center;
background-size: cover;
}
</style>
<body>
<div class="bgimg w3-display-container w3-animate-opacity w3-text-white">
<div class="w3-display-middle">
<h1 class="w3-jumbo w3-animate-top">HAPPY BOTDAY!</h1>
<hr class="w3-border-grey" style="margin:auto;width:40%">
<p class="w3-large w3-center">Va sur <a href="https://t.me/happyCSbot">t.me/happyCSbot</a> pour la configuration.
</p>
</div>
</div>
</body>
</html>
\ No newline at end of file
require('./telegram'); const bot = require('./telegram');
\ No newline at end of file const app = require('./website');
const mongoose = require('./mongoose');
const Token = require('./models/Token');
const rp = require('request-promise');
function sendRequest(req, token, callback) {
const options = {
headers: { 'Authorization': `Bearer ${token}` },
json: true
}
const url = 'https://gateway.linkcs.fr/v1/graphql';
return rp(`${url}?query=${req}`, options)
}
function getBirthdays(token) {
req = 'query getUsersBirthday {users: usersBirthday { ...userData}}fragment userData on User {id firstName lastName roles {sector {composition {association {id}}}}}'
return sendRequest(req, token).then(body => {
const users = [];
body.data.users.forEach(user => {
use = {};
use.name = `${user.firstName} ${user.lastName}`;
use.asso = [];
user.roles.forEach(role => {
use.asso.push(role.sector.composition.association.id);
})
users.push(use);
});
return users;
})
}
// Token.findOne({ expiration: { $gt: Date.now() } }).then(token => {
// getBirthdays(token.token).then(a => console.log(a));
// })
\ No newline at end of file
const mongoose = require('../mongoose');
const tokenSchema = new mongoose.Schema({
token: String,
expiration: Date,
username: String,
chatId: Number,
state: String
})
module.exports = mongoose.model('Token', tokenSchema);
\ No newline at end of file
...@@ -2,7 +2,7 @@ const mongoose = require('mongoose'); ...@@ -2,7 +2,7 @@ const mongoose = require('mongoose');
mongoose.Promise = global.Promise; mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/botday') mongoose.connect('mongodb://localhost/botday', { useNewUrlParser: true })
.then(() => console.log('[mongoose] Connection succesful')) .then(() => console.log('[mongoose] Connection succesful'))
.catch((err) => console.error(err)); .catch((err) => console.error(err));
......
This diff is collapsed.
...@@ -19,6 +19,10 @@ ...@@ -19,6 +19,10 @@
"author": "capsule_man", "author": "capsule_man",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"node-telegram-bot-api": "^0.30.0" "express": "^4.16.4",
"mongoose": "^5.4.12",
"node-telegram-bot-api": "^0.30.0",
"request": "^2.88.0",
"request-promise": "^4.2.4"
} }
} }
process.env["NTBA_FIX_319"] = 1;
const TelegramBot = require('node-telegram-bot-api'); const TelegramBot = require('node-telegram-bot-api');
const Token = require('./models/Token');
const config = require('./config'); const config = require('./config');
...@@ -6,13 +8,49 @@ const config = require('./config'); ...@@ -6,13 +8,49 @@ const config = require('./config');
const bot = new TelegramBot(config.telegram.token, { polling: true }); const bot = new TelegramBot(config.telegram.token, { polling: true });
bot.onText(/\/start/, (msg, _) => { bot.onText(/\/start/, (msg, _) => {
console.log(msg);
const chatId = msg.chat.id; const chatId = msg.chat.id;
const resp = 'Holà, je suis le happy botday, je suis là pour vous souhaiter vous rapeller les anniversaires de vos potes !\nPour commencer, il faut que quelqu\'un s\'identifie : /connect'; const resp = 'Holà, je suis le Happy Botday, je suis là pour vous souhaiter vous rapeller les anniversaires de vos potes !\nPour commencer, il faut que quelqu\'un s\'identifie : /connect';
bot.sendMessage(chatId, resp); bot.sendMessage(chatId, resp);
}); });
bot.onText(/\/connect/, (msg, _) => { bot.onText(/\/connect/, (msg, _) => {
const chatId = msg.chat.id; const chatId = msg.chat.id;
const resp = `Pour vous identifier, connectez-vous via l\'OAuth2 de ViaRézo depuis ce lien : ${config.website.protocol}://${config.website.url}/${chatId}`; const state = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
Token.findOne({
chatId: chatId
}).then(token => {
if (!token) {
return Token.create({
username: msg.from.username,
chatId: chatId,
state: state
})
} else if (!token.token) {
return Token.findByIdAndDelete(token._id).then(_ => {
return Token.create({
username: msg.from.username,
chatId: chatId,
state: state
})
})
} else {
bot.sendMessage(chatId, `Une connexion a déjà été faite par @${token.username}. Pour la réinitialiser, faites /disconnect`);
}
}).then(token => {
if (!token) return
const resp = `Pour vous identifier, connectez-vous via l\'OAuth2 de ViaRézo depuis ce lien :\n${config.website.protocol}://${config.website.hostname}/?state=${state}`;
bot.sendMessage(chatId, resp); bot.sendMessage(chatId, resp);
})
}); });
bot.onText(/\/disconnect/, (msg, _) => {
const chatId = msg.chat.id;
Token.findOneAndDelete({ chatId: chatId }).then(token => {
if (!token) return bot.sendMessage(chatId, 'Pas de compte connecté');
const resp = `@${token.username} n'est plus connecté à l'OAuth2.`;
bot.sendMessage(chatId, resp);
})
});
module.exports = bot;
\ No newline at end of file
const config = require('./config');
const app = require('express')();
const request = require('request');
const bot = require('./telegram');
const Token = require('./models/Token');
app.listen(80, config.website.hostname, () => {
console.log(`[express] Website is up and accessible on ${config.website.protocol}://${config.website.hostname}/`);
})
app.get('/', function (req, res) {
if (!req.query.state) { return res.sendFile(`${__dirname}/index.html`) };
Token.findOne({ state: req.query.state }).then(rep => {
if (!rep || rep.token) return res.sendFile(`${__dirname}/index.html`);
const redirectURI = `${config.website.protocol}://${config.website.hostname}/auth`;
const url = `https://auth.viarezo.fr/oauth/authorize/?redirect_uri=${redirectURI}&client_id=${config.oauth2.clientid}&response_type=code&state=${rep.state}&scope=${config.oauth2.scope}`;
return res.redirect(301, url);
})
})
app.get('/background.jpg', function (req, res) {
res.sendFile(`${__dirname}/background.jpg`)
})
app.get('/auth', function (req, res) {
if (!req.query.code || !req.query.state) return res.sendFile(`${__dirname}/auth.html`)
const options = {
url: 'https://auth.viarezo.fr/oauth/token',
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
form: {
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: config.website.protocol + '://' + config.website.hostname + '/auth',
client_id: config.oauth2.clientid,
client_secret: config.oauth2.secretid
}
}
request(options, (err, res, body) => {
if (!err && res.statusCode == 200) {
Token.findOne({ state: req.query.state }).then(token => {
rep = JSON.parse(body)
if (!token) { return req.query.state }
token.token = rep.access_token;
token.expiration = rep.expires_at*1000;
token.state = '';
return token.save();
}).then(token => {
bot.sendMessage(token.chatId, `@${token.username} s'est connecté à OAuth2, shall we begin?`)
})
}
})
return res.redirect(301, `${config.website.protocol}://${config.website.hostname}/auth`);
})
module.exports = app;
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment