i am unable to get the current user from a function i created.
What i want to do?
I created a function called /api/colab that accepts a body with a room id, the goal is that I am able to get the currentUser in the function and extract the id and fullname.
What i tried;
- tried using the getCurrentUser(session_toke) but got invalid token error
- tried to pass the token from the web side but still got the same error
So my questions;
- how do you handle authentication on the functions
- how do you get the current user
We’ve added this function in lib/auth
that you can call from your function to initialize the context:
/*
* To use in other(not graphql) functions.
* Provides only the user id, and the user object can be loaded after if needed.
* To remove when RedwoodJS provides a solution
*/
export const initFunctionSession = (event: APIGatewayEvent): void => {
const cookie = extractCookie(event)
if (cookie) {
const encryptedSession = getSession(cookie)
if (encryptedSession) {
const [session, _csrfToken] = decryptSession(encryptedSession)
context.currentUser = { ...session }
}
}
}
1 Like
Hi @amkayondo i think you may want to see how to wrap your function in “useRequireAuth” as described in the following documentation: Serverless Functions | RedwoodJS Docs
2 Likes
thank you, let me try it out and get back to you
how do you handle this section for dbAuth
I mean this part on the frontend
Authorization: Bearer myJWT.accesstoken.signature
auth-provider: supabase
Content-Type: application/json
// room.tsx
am i retrieving the token the right way and also it seems the token is not the access token and how do i retrieve the access token on the web side without usind hooks
const [token, setToken] = useState('')
const { currentUser, getToken } = useAuth()
const _token = async () => {
const data = await getToken()
setToken(data)
}
useEffect(() => {
_token()
return () => {}
}, [])
<RoomProvider
initialStorage={{}}
id={`roomid=${roomId}&token=${token}`}
initialPresence={{}}
>
// live blocks client
const client = createClient({
// publicApiKey: ""
// authEndpoint: "/api/auth",
// throttle: 100,
authEndpoint: async (room) => {
console.log('asd', room)
const keyValuePairs = room.split('&')
const jsonObject: {
roomid: string
token: string
} = {}
keyValuePairs.forEach((pair) => {
const [key, value] = pair.split('=')
jsonObject[key] = value
})
return await axios
.post(
'/api/colab',
{
room: jsonObject?.roomid,
},
{
headers: {
Authorization: `Bearer ${jsonObject.token}`,
'auth-provider': 'dbAuth',
'Content-Type': 'application/json',
},
}
)
.then((res) => {
return res.data
})
},
})