Skip to content

Instantly share code, notes, and snippets.

@sarjsheff
Last active June 7, 2020 12:38
Show Gist options
  • Select an option

  • Save sarjsheff/93076a97bd1d58a7652e21d0236cf821 to your computer and use it in GitHub Desktop.

Select an option

Save sarjsheff/93076a97bd1d58a7652e21d0236cf821 to your computer and use it in GitHub Desktop.
Authorization react + socket.io
import React, { useState, useEffect } from "react";
import * as io from "socket.io-client";
const socket = io();
function Auth() {
const [auth, setAuth] = useState(false);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [name, setName] = useState("");
useEffect(() => {
socket.on("authed", (data) => {
setAuth(data);
if (data) socket.emit("getusername");
});
socket.on("username", (data) => {
setName(data);
});
});
const doLogin = (e) => {
socket.emit("login", { username: username, password: password });
};
return (
<div>
{auth ? (
<div>Logged {name}</div>
) : (
<div>
<div>Username:</div>
<div>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>Password:</div>
<div>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div>
<button onClick={doLogin}>Login</button>
</div>
</div>
)}
</div>
);
}
export default Auth;
var app = require("express")();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
var authedSessions = {};
io.on("connection", (socket) => {
socket.emit("auth", false);
socket.on("login", (data) => {
if (data.username == "test" && data.password == "password") {
authedSessions[socket.id] = "Test";
socket.emit("authed", true);
} else {
socket.emit("authed", false);
}
});
socket.on("getusername", (data) => {
const username = authedSessions[socket.id];
if (username) {
socket.emit("username", username);
} else {
socket.emit("auth", false);
}
});
socket.on("disconnect", function () {
delete authedSessions[socket.id];
});
});
http.listen(3333, () => {
console.log("listening on *:3333");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment