Authentication
This section covers the configuration and usage of @colyseus/social
.
@colyseus/social
is an experimental module that provides general-purpose backend services to speed-up your multiplayer game development experience. The API is open for suggestions and improvement.
Tip
If you're looking to implement your own authentication method, see Server API ยป Authentication
Installation¶
-
Install the
@colyseus/social
module.
npm install @colyseus/social
npm install express-jwt
- Import and expose the Express routes provided by
@colyseus/social
.
import express from "express";
import socialRoutes from "@colyseus/social/express"
const app = express();
app.use("/", socialRoutes);
app.listen(8080);
Server-side configuration¶
Environment Variables¶
MONGO_URI
: MongoDB connection URIJWT_SECRET
: Secure secret string for authentication.FACEBOOK_APP_TOKEN
: Facebook App Token ("appid|appsecret"
)
Server-side API¶
The @colyseus/social
module provides the MongoDB models, and the token validation function available for you to use.
import { User, FriendRequest, verifyToken } from "@colyseus/social";
Implementing onAuth
to retrieve the current user¶
import { User, verifyToken } from "@colyseus/social";
class MyRoom extends Room {
async onAuth(client, options) {
// verify token authenticity
const token = verifyToken(options.token);
// query the user by its id
return await User.findById(token._id);
}
onJoin(client, options, user) {
console.log(user.username, "has joined the room!");
}
}
Hooks¶
hooks.beforeAuthenticate
¶
The beforeAuthenticate
hook is triggered before a user logs in or registers.
import { hooks } from "@colyseus/social";
hooks.beforeAuthenticate((provider, $setOnInsert, $set) => {
// assign default metadata upon registration
$setOnInsert.metadata = {
coins: 100,
trophies: 0
};
});
hooks.beforeUserUpdate
¶
The beforeUserUpdate
hooks is triggered before a user update his own information through the save() method.
import Filter from "bad-words";
const filter = new Filter();
hooks.beforeUserUpdate((_id, fields) => {
if (fields['username'] && filter.isProfane(fields['username'])) {
throw new Error("no_swearing_allowed");
}
})
Client-side API¶
Login¶
Anonymous¶
await client.auth.login();
await client.Auth.Login();
client.auth:login(function(err, auth)
-- ...
end);
Email + Password¶
await client.auth.login({
email: "user@example.com",
password: "12345"
});
await client.Auth.Login("user@example.com", "12345");
client.auth:login({
email = "user@example.com",
password = "12345"
}, function(err, auth)
-- ...
end)
Facebook¶
//
// Make sure you have the Facebook SDK installed and configured first
// - https://developers.facebook.com/docs/javascript/quickstart
// - https://developers.facebook.com/docs/facebook-login/web
//
FB.login(function(response) {
if (response.authResponse) {
client.auth.login({ accessToken: response.authResponse.accessToken });
}
}, { scope: 'public_profile,email,user_friends' });
//
// Make sure you have the Facebook SDK installed and configured first
// - https://developers.facebook.com/docs/unity/gettingstarted
// - https://developers.facebook.com/docs/unity/examples#login
//
var perms = new List<string>(){"public_profile", "email", "user_friends"};
FB.LogInWithReadPermissions(perms, AuthCallback);
private void AuthCallback (ILoginResult result) {
if (FB.IsLoggedIn) {
client.Auth.Login(Facebook.Unity.AccessToken.CurrentAccessToken);
}
}
client.auth:facebook_login(function(err, auth)
pprint(auth)
end)
Update User Data¶
You can modify the username
, displayName
, avatarUrl
, lang
, location
, and timezone
from the client-side, and then call the save()
method.
client.auth.username = "Hello world!"
await client.auth.save();
client.Auth.Username = "Hello world!";
await client.Auth.Save();
client.auth.username = "Hello world!"
client.auth:save()
Logout¶
client.auth.logout();
client.Auth.Logout();
client.auth:logout();
Get Friends¶
const friends = await client.auth.getFriends();
friends.forEach(friend => {
console.log(friend.username);
});
var friends = await client.Auth.GetFriends();
for (var i=0; i<friends.Length; i++)
{
Debug.Log(friends[i].Username);
}
client.auth:get_friends(function(err, friends)
for i, friend in pairs(friends) do
print(friend.username)
end
end);
Get Online Friends¶
const friends = await client.auth.getOnlineFriends();
friends.forEach(friend => {
console.log(friend.username);
});
var friends = await client.Auth.GetOnlineFriends();
for (var i=0; i<friends.Length; i++)
{
Debug.Log(friends[i].Username);
}
client.auth:get_online_friends(function(err, friends)
for i, friend in pairs(friends) do
print(friend.username)
end
end);
Get Friend Requests¶
const friends = await client.auth.getFriendRequests();
friends.forEach(friend => {
console.log(friend.username);
});
var friends = await client.Auth.GetFriendRequests();
for (var i=0; i<friends.Length; i++)
{
Debug.Log(friends[i].Username);
}
client.auth:get_friend_requests(function(err, friends)
for i, friend in pairs(friends) do
print(friend.username)
end
end);
Accept Friend Request¶
await client.auth.acceptFriendRequest(friendId);
await client.Auth.AcceptFriendRequest(friendId);
client.auth:accept_friend_request(friend_id)
Decline Friend Request¶
await client.auth.declineFriendRequest(friendId);
await client.Auth.DeclineFriendRequest(friendId);
client.auth:decline_friend_request(friend_id)
Send Friend Request¶
await client.auth.sendFriendRequest(friendId);
await client.Auth.SendFriendRequest(friendId);
client.auth:send_friend_request(friend_id)
Block User¶
await client.auth.blockUser(friendId);
await client.Auth.BlockUser(friendId);
client.auth:block_user(friend_id)
Unblock User¶
await client.auth.unblockUser(friendId);
await client.Auth.UnblockUser(friendId);
client.auth:unblock_user(friend_id)