2022-10-19 15:40:28 +03:00
// Copyright 2022 The Gitea Authors. All rights reserved.
2022-11-27 21:20:29 +03:00
// SPDX-License-Identifier: MIT
2022-10-19 15:40:28 +03:00
package mailer
import (
"bytes"
"context"
2023-08-31 19:26:13 +03:00
"fmt"
"net/url"
2022-10-19 15:40:28 +03:00
org_model "code.gitea.io/gitea/models/organization"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/translation"
2024-11-30 04:15:41 +03:00
sender_service "code.gitea.io/gitea/services/mailer/sender"
2022-10-19 15:40:28 +03:00
)
const (
tplTeamInviteMail base . TplName = "team_invite"
)
// MailTeamInvite sends team invites
func MailTeamInvite ( ctx context . Context , inviter * user_model . User , team * org_model . Team , invite * org_model . TeamInvite ) error {
if setting . MailService == nil {
return nil
}
2022-12-03 05:48:26 +03:00
org , err := user_model . GetUserByID ( ctx , team . OrgID )
2022-10-19 15:40:28 +03:00
if err != nil {
return err
}
locale := translation . NewLocale ( inviter . Language )
2023-08-31 19:26:13 +03:00
// check if a user with this email already exists
user , err := user_model . GetUserByEmail ( ctx , invite . Email )
if err != nil && ! user_model . IsErrUserNotExist ( err ) {
return err
} else if user != nil && user . ProhibitLogin {
return fmt . Errorf ( "login is prohibited for the invited user" )
}
inviteRedirect := url . QueryEscape ( fmt . Sprintf ( "/org/invite/%s" , invite . Token ) )
inviteURL := fmt . Sprintf ( "%suser/sign_up?redirect_to=%s" , setting . AppURL , inviteRedirect )
2023-09-07 17:50:45 +03:00
if ( err == nil && user != nil ) || setting . Service . DisableRegistration || setting . Service . AllowOnlyExternalRegistration {
// user account exists or registration disabled
2023-08-31 19:26:13 +03:00
inviteURL = fmt . Sprintf ( "%suser/login?redirect_to=%s" , setting . AppURL , inviteRedirect )
}
2024-02-15 00:48:45 +03:00
subject := locale . TrString ( "mail.team_invite.subject" , inviter . DisplayName ( ) , org . DisplayName ( ) )
2023-07-04 21:36:08 +03:00
mailMeta := map [ string ] any {
2023-10-31 17:11:48 +03:00
"locale" : locale ,
2022-10-19 15:40:28 +03:00
"Inviter" : inviter ,
"Organization" : org ,
"Team" : team ,
"Invite" : invite ,
"Subject" : subject ,
2023-08-31 19:26:13 +03:00
"InviteURL" : inviteURL ,
2022-10-19 15:40:28 +03:00
}
var mailBody bytes . Buffer
if err := bodyTemplates . ExecuteTemplate ( & mailBody , string ( tplTeamInviteMail ) , mailMeta ) ; err != nil {
log . Error ( "ExecuteTemplate [%s]: %v" , string ( tplTeamInviteMail ) + "/body" , err )
return err
}
2024-11-30 04:15:41 +03:00
msg := sender_service . NewMessage ( invite . Email , subject , mailBody . String ( ) )
2022-10-19 15:40:28 +03:00
msg . Info = subject
SendAsync ( msg )
return nil
}